CacheItem.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace Doctrine\Common\Cache\Psr6;
  3. use DateInterval;
  4. use DateTime;
  5. use DateTimeInterface;
  6. use Psr\Cache\CacheItemInterface;
  7. use TypeError;
  8. use function get_class;
  9. use function gettype;
  10. use function is_int;
  11. use function is_object;
  12. use function microtime;
  13. use function sprintf;
  14. final class CacheItem implements CacheItemInterface
  15. {
  16. /** @var string */
  17. private $key;
  18. /** @var mixed */
  19. private $value;
  20. /** @var bool */
  21. private $isHit;
  22. /** @var float|null */
  23. private $expiry;
  24. /**
  25. * @internal
  26. *
  27. * @param mixed $data
  28. */
  29. public function __construct(string $key, $data, bool $isHit)
  30. {
  31. $this->key = $key;
  32. $this->value = $data;
  33. $this->isHit = $isHit;
  34. }
  35. public function getKey(): string
  36. {
  37. return $this->key;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. *
  42. * @return mixed
  43. */
  44. public function get()
  45. {
  46. return $this->value;
  47. }
  48. public function isHit(): bool
  49. {
  50. return $this->isHit;
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. public function set($value): self
  56. {
  57. $this->value = $value;
  58. return $this;
  59. }
  60. /**
  61. * {@inheritDoc}
  62. */
  63. public function expiresAt($expiration): self
  64. {
  65. if ($expiration === null) {
  66. $this->expiry = null;
  67. } elseif ($expiration instanceof DateTimeInterface) {
  68. $this->expiry = (float) $expiration->format('U.u');
  69. } else {
  70. throw new TypeError(sprintf(
  71. 'Expected $expiration to be an instance of DateTimeInterface or null, got %s',
  72. is_object($expiration) ? get_class($expiration) : gettype($expiration)
  73. ));
  74. }
  75. return $this;
  76. }
  77. /**
  78. * {@inheritDoc}
  79. */
  80. public function expiresAfter($time): self
  81. {
  82. if ($time === null) {
  83. $this->expiry = null;
  84. } elseif ($time instanceof DateInterval) {
  85. $this->expiry = microtime(true) + DateTime::createFromFormat('U', 0)->add($time)->format('U.u');
  86. } elseif (is_int($time)) {
  87. $this->expiry = $time + microtime(true);
  88. } else {
  89. throw new TypeError(sprintf(
  90. 'Expected $time to be either an integer, an instance of DateInterval or null, got %s',
  91. is_object($time) ? get_class($time) : gettype($time)
  92. ));
  93. }
  94. return $this;
  95. }
  96. /**
  97. * @internal
  98. */
  99. public function getExpiry(): ?float
  100. {
  101. return $this->expiry;
  102. }
  103. }