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