ArrayLock.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Illuminate\Support\Carbon;
  4. class ArrayLock extends Lock
  5. {
  6. /**
  7. * The parent array cache store.
  8. *
  9. * @var \Illuminate\Cache\ArrayStore
  10. */
  11. protected $store;
  12. /**
  13. * Create a new lock instance.
  14. *
  15. * @param \Illuminate\Cache\ArrayStore $store
  16. * @param string $name
  17. * @param int $seconds
  18. * @param string|null $owner
  19. * @return void
  20. */
  21. public function __construct($store, $name, $seconds, $owner = null)
  22. {
  23. parent::__construct($name, $seconds, $owner);
  24. $this->store = $store;
  25. }
  26. /**
  27. * Attempt to acquire the lock.
  28. *
  29. * @return bool
  30. */
  31. public function acquire()
  32. {
  33. $expiration = $this->store->locks[$this->name]['expiresAt'] ?? Carbon::now()->addSecond();
  34. if ($this->exists() && $expiration->isFuture()) {
  35. return false;
  36. }
  37. $this->store->locks[$this->name] = [
  38. 'owner' => $this->owner,
  39. 'expiresAt' => $this->seconds === 0 ? null : Carbon::now()->addSeconds($this->seconds),
  40. ];
  41. return true;
  42. }
  43. /**
  44. * Determine if the current lock exists.
  45. *
  46. * @return bool
  47. */
  48. protected function exists()
  49. {
  50. return isset($this->store->locks[$this->name]);
  51. }
  52. /**
  53. * Release the lock.
  54. *
  55. * @return bool
  56. */
  57. public function release()
  58. {
  59. if (! $this->exists()) {
  60. return false;
  61. }
  62. if (! $this->isOwnedByCurrentProcess()) {
  63. return false;
  64. }
  65. $this->forceRelease();
  66. return true;
  67. }
  68. /**
  69. * Returns the owner value written into the driver for this lock.
  70. *
  71. * @return string
  72. */
  73. protected function getCurrentOwner()
  74. {
  75. if (! $this->exists()) {
  76. return null;
  77. }
  78. return $this->store->locks[$this->name]['owner'];
  79. }
  80. /**
  81. * Releases this lock in disregard of ownership.
  82. *
  83. * @return void
  84. */
  85. public function forceRelease()
  86. {
  87. unset($this->store->locks[$this->name]);
  88. }
  89. }