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