Lock.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Illuminate\Support\InteractsWithTime;
  4. use Illuminate\Contracts\Cache\LockTimeoutException;
  5. abstract class Lock
  6. {
  7. use InteractsWithTime;
  8. /**
  9. * The name of the lock.
  10. *
  11. * @var string
  12. */
  13. protected $name;
  14. /**
  15. * The number of seconds the lock should be maintained.
  16. *
  17. * @var int
  18. */
  19. protected $seconds;
  20. /**
  21. * Create a new lock instance.
  22. *
  23. * @param string $name
  24. * @param int $seconds
  25. * @return void
  26. */
  27. public function __construct($name, $seconds)
  28. {
  29. $this->name = $name;
  30. $this->seconds = $seconds;
  31. }
  32. /**
  33. * Attempt to acquire the lock.
  34. *
  35. * @return bool
  36. */
  37. abstract public function acquire();
  38. /**
  39. * Attempt to acquire the lock.
  40. *
  41. * @param callable|null $callback
  42. * @return bool
  43. */
  44. public function get($callback = null)
  45. {
  46. $result = $this->acquire();
  47. if ($result && is_callable($callback)) {
  48. return tap($callback(), function () {
  49. $this->release();
  50. });
  51. }
  52. return $result;
  53. }
  54. /**
  55. * Attempt to acquire the lock for the given number of seconds.
  56. *
  57. * @param int $seconds
  58. * @param callable|null $callback
  59. * @return bool
  60. * @throws \Illuminate\Contracts\Cache\LockTimeoutException
  61. */
  62. public function block($seconds, $callback = null)
  63. {
  64. $starting = $this->currentTime();
  65. while (! $this->acquire()) {
  66. usleep(250 * 1000);
  67. if ($this->currentTime() - $seconds >= $starting) {
  68. throw new LockTimeoutException;
  69. }
  70. }
  71. if (is_callable($callback)) {
  72. return tap($callback(), function () {
  73. $this->release();
  74. });
  75. }
  76. return true;
  77. }
  78. }