vendor/symfony/lock/Key.php line 21

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Lock;
  11. use Symfony\Component\Lock\Exception\UnserializableKeyException;
  12. /**
  13. * Key is a container for the state of the locks in stores.
  14. *
  15. * @author Jérémy Derussé <jeremy@derusse.com>
  16. */
  17. final class Key
  18. {
  19. private $resource;
  20. private $expiringTime;
  21. private $state = [];
  22. private $serializable = true;
  23. public function __construct(string $resource)
  24. {
  25. $this->resource = $resource;
  26. }
  27. public function __toString(): string
  28. {
  29. return $this->resource;
  30. }
  31. public function hasState(string $stateKey): bool
  32. {
  33. return isset($this->state[$stateKey]);
  34. }
  35. public function setState(string $stateKey, $state): void
  36. {
  37. $this->state[$stateKey] = $state;
  38. }
  39. public function removeState(string $stateKey): void
  40. {
  41. unset($this->state[$stateKey]);
  42. }
  43. public function getState(string $stateKey)
  44. {
  45. return $this->state[$stateKey];
  46. }
  47. public function markUnserializable(): void
  48. {
  49. $this->serializable = false;
  50. }
  51. public function resetLifetime()
  52. {
  53. $this->expiringTime = null;
  54. }
  55. /**
  56. * @param float $ttl the expiration delay of locks in seconds
  57. */
  58. public function reduceLifetime(float $ttl)
  59. {
  60. $newTime = microtime(true) + $ttl;
  61. if (null === $this->expiringTime || $this->expiringTime > $newTime) {
  62. $this->expiringTime = $newTime;
  63. }
  64. }
  65. /**
  66. * Returns the remaining lifetime in seconds.
  67. */
  68. public function getRemainingLifetime(): ?float
  69. {
  70. return null === $this->expiringTime ? null : $this->expiringTime - microtime(true);
  71. }
  72. public function isExpired(): bool
  73. {
  74. return null !== $this->expiringTime && $this->expiringTime <= microtime(true);
  75. }
  76. public function __sleep(): array
  77. {
  78. if (!$this->serializable) {
  79. throw new UnserializableKeyException('The key cannot be serialized.');
  80. }
  81. return ['resource', 'expiringTime', 'state'];
  82. }
  83. }