|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illuminate\Cache; |
| 4 | + |
| 5 | +use Carbon\Carbon; |
| 6 | +use Illuminate\Contracts\Cache\LockTimeoutException; |
| 7 | + |
| 8 | +abstract class Lock |
| 9 | +{ |
| 10 | + /** |
| 11 | + * Attempt to acquire the lock. |
| 12 | + * |
| 13 | + * @return bool |
| 14 | + */ |
| 15 | + abstract public function acquire(); |
| 16 | + |
| 17 | + /** |
| 18 | + * Attempt to acquire the lock. |
| 19 | + * |
| 20 | + * @param callable|null $callback |
| 21 | + * @return bool |
| 22 | + */ |
| 23 | + public function get($callback = null) |
| 24 | + { |
| 25 | + $result = $this->acquire(); |
| 26 | + |
| 27 | + if ($result && is_callable($callback)) { |
| 28 | + return tap($callback(), function () { |
| 29 | + $this->release(); |
| 30 | + }); |
| 31 | + } |
| 32 | + |
| 33 | + return $result; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Attempt to acquire the lock while blocking indefinitely. |
| 38 | + * |
| 39 | + * @param callable|null $calback |
| 40 | + * @return bool |
| 41 | + */ |
| 42 | + public function block($callback = null) |
| 43 | + { |
| 44 | + while (! $this->acquire()) { |
| 45 | + usleep(250 * 1000); |
| 46 | + } |
| 47 | + |
| 48 | + if (is_callable($callback)) { |
| 49 | + return tap($callback(), function () { |
| 50 | + $this->release(); |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + return true; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Attempt to acquire the lock for the given number of seconds. |
| 59 | + * |
| 60 | + * @param int $seconds |
| 61 | + * @param callable|null $callback |
| 62 | + * @return bool |
| 63 | + */ |
| 64 | + public function blockFor($seconds, $callback = null) |
| 65 | + { |
| 66 | + $starting = Carbon::now(); |
| 67 | + |
| 68 | + while (! $this->acquire()) { |
| 69 | + usleep(250 * 1000); |
| 70 | + |
| 71 | + if (Carbon::now()->subSeconds($seconds)->gte($starting)) { |
| 72 | + throw new LockTimeoutException; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if (is_callable($callback)) { |
| 77 | + return tap($callback(), function () { |
| 78 | + $this->release(); |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + return true; |
| 83 | + } |
| 84 | +} |
0 commit comments