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 12namespace Symfony\Component\Lock; 13 14/** 15 * Key is a container for the state of the locks in stores. 16 * 17 * @author Jérémy Derussé <jeremy@derusse.com> 18 */ 19final class Key 20{ 21 private $resource; 22 private $expiringTime; 23 private $state = []; 24 25 /** 26 * @param string $resource 27 */ 28 public function __construct($resource) 29 { 30 $this->resource = (string) $resource; 31 } 32 33 public function __toString() 34 { 35 return $this->resource; 36 } 37 38 /** 39 * @param string $stateKey 40 * 41 * @return bool 42 */ 43 public function hasState($stateKey) 44 { 45 return isset($this->state[$stateKey]); 46 } 47 48 /** 49 * @param string $stateKey 50 * @param mixed $state 51 */ 52 public function setState($stateKey, $state) 53 { 54 $this->state[$stateKey] = $state; 55 } 56 57 /** 58 * @param string $stateKey 59 */ 60 public function removeState($stateKey) 61 { 62 unset($this->state[$stateKey]); 63 } 64 65 /** 66 * @param $stateKey 67 * 68 * @return mixed 69 */ 70 public function getState($stateKey) 71 { 72 return $this->state[$stateKey]; 73 } 74 75 public function resetLifetime() 76 { 77 $this->expiringTime = null; 78 } 79 80 /** 81 * @param float $ttl the expiration delay of locks in seconds 82 */ 83 public function reduceLifetime($ttl) 84 { 85 $newTime = microtime(true) + $ttl; 86 87 if (null === $this->expiringTime || $this->expiringTime > $newTime) { 88 $this->expiringTime = $newTime; 89 } 90 } 91 92 /** 93 * Returns the remaining lifetime. 94 * 95 * @return float|null Remaining lifetime in seconds. Null when the key won't expire. 96 */ 97 public function getRemainingLifetime() 98 { 99 return null === $this->expiringTime ? null : $this->expiringTime - microtime(true); 100 } 101 102 /** 103 * @return bool 104 */ 105 public function isExpired() 106 { 107 return null !== $this->expiringTime && $this->expiringTime <= microtime(true); 108 } 109} 110