ExtendedCacheItemTrait::getCreationDate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 *
5
 * This file is part of Phpfastcache.
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
10
 *
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 * @author Contributors  https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
13
 */
14
15
declare(strict_types=1);
16
17
namespace Phpfastcache\Core\Item;
18
19
use DateTime;
20
use DateTimeInterface;
21
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
22
use Phpfastcache\Event\EventManagerInterface;
23
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
24
use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException;
25
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
26
27
trait ExtendedCacheItemTrait
28
{
29
    use CacheItemTrait;
30
31
    protected ExtendedCacheItemPoolInterface $driver;
32
33
    protected string $encodedKey;
34
35
    /**
36
     * Item constructor.
37
     * @param ExtendedCacheItemPoolInterface $driver
38
     * @param string $key
39
     * @param EventManagerInterface $em
40
     * @throws PhpfastcacheInvalidArgumentException
41
     */
42
    public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em)
43
    {
44
        $this->data = null;
45
        $this->key = $key;
46
        $this->setEventManager($em);
47
        $this->setDriver($driver);
48
        if ($driver->getConfig()->isUseStaticItemCaching()) {
49
            $this->driver->setItem($this);
50
        }
51
        $this->expirationDate = new DateTime();
52
        if ($this->driver->getConfig()->isItemDetailedDate()) {
53
            $this->creationDate = new DateTime();
54
            $this->modificationDate = new DateTime();
55
        }
56
    }
57
58
    /**
59
     * @param ExtendedCacheItemPoolInterface $driver
60
     * @return ExtendedCacheItemInterface
61
     * @throws PhpfastcacheInvalidArgumentException
62
     */
63
    public function setDriver(ExtendedCacheItemPoolInterface $driver): ExtendedCacheItemInterface
64
    {
65
        $driverClass = $this->getDriverClass();
66
        if ($driver instanceof $driverClass) {
67
            $this->driver = $driver;
68
69
            return $this;
70
        }
71
72
        throw new PhpfastcacheInvalidArgumentException(\sprintf('Invalid driver instance "%s" for cache item "%s"', $driver::class, static::class));
73
    }
74
75
    /**
76
     * @inheritDoc
77
     */
78
    public function getEncodedKey(): string
79
    {
80
        if (!isset($this->encodedKey)) {
81
            $this->encodedKey = $this->driver->getEncodedKey($this->getKey());
82
        }
83
84
        return $this->encodedKey;
85
    }
86
87
    /**
88
     * @inheritDoc
89
     * @SuppressWarnings(PHPMD.CamelCaseMethodName)
90
     */
91
    public function _getData(): mixed // @phpcs:ignore
92
    {
93
        return $this->data;
94
    }
95
96
    /**
97
     * @inheritDoc
98
     */
99
    public function getExpirationDate(): DateTimeInterface
100
    {
101
        return $this->expirationDate;
102
    }
103
104
    /**
105
     * @inheritDoc
106
     * @throws PhpfastcacheInvalidArgumentException
107
     */
108
    public function setExpirationDate(DateTimeInterface $expiration): ExtendedCacheItemInterface
109
    {
110
        return $this->expiresAt($expiration);
111
    }
112
113
    /**
114
     * @inheritDoc
115
     * @throws PhpfastcacheLogicException
116
     */
117
    public function getCreationDate(): DateTimeInterface
118
    {
119
        if ($this->driver->getConfig()->isItemDetailedDate()) {
120
            return $this->creationDate;
121
        }
122
123
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
124
    }
125
126
    /**
127
     * @inheritDoc
128
     * @throws PhpfastcacheLogicException
129
     */
130
    public function setCreationDate(DateTimeInterface $date): ExtendedCacheItemInterface
131
    {
132
        if ($this->driver->getConfig()->isItemDetailedDate()) {
133
            $this->creationDate = $this->demutateDatetime($date);
134
            return $this;
135
        }
136
137
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
138
    }
139
140
    /**
141
     * @inheritDoc
142
     * @throws PhpfastcacheLogicException
143
     */
144
    public function getModificationDate(): DateTimeInterface
145
    {
146
        if ($this->driver->getConfig()->isItemDetailedDate()) {
147
            return $this->modificationDate;
148
        }
149
150
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
151
    }
152
153
    /**
154
     * @inheritDoc
155
     * @throws PhpfastcacheLogicException
156
     */
157
    public function setModificationDate(DateTimeInterface $date): ExtendedCacheItemInterface
158
    {
159
        if ($this->driver->getConfig()->isItemDetailedDate()) {
160
            $this->modificationDate = $this->demutateDatetime($date);
161
            return $this;
162
        }
163
164
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
165
    }
166
167
    public function getTtl(): int
168
    {
169
        return \max(0, $this->expirationDate->getTimestamp() - \time());
170
    }
171
172
    public function isExpired(): bool
173
    {
174
        return $this->getTtl() <= 0;
175
    }
176
177
    public function isNull(): bool
178
    {
179
        return $this->get() === null;
180
    }
181
182
    public function isEmpty(): bool
183
    {
184
        return empty($this->get());
185
    }
186
187
    /**
188
     * Return the data length:
189
     * Either the string length if it's a string (binary mode)
190
     * # or the number of element (count) if it's an array
191
     * # or the number returned by count() if it's an object implementing \Countable interface
192
     * # -1 for anything else
193
     * @return int
194
     */
195
    public function getLength(): int
196
    {
197
        switch (\gettype($this->data)) {
198
            case 'array':
199
            case 'object':
200
                if (\is_countable($this->data)) {
201
                    return \count($this->data);
202
                }
203
                break;
204
205
            case 'string':
206
                return \strlen($this->data);
207
        }
208
209
        return -1;
210
    }
211
212
    /**
213
     * @throws PhpfastcacheInvalidTypeException
214
     */
215
    public function increment(int $step = 1): ExtendedCacheItemInterface
216
    {
217
        if ($this->data !== null && !\is_numeric($this->data)) {
218
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot increment on a "%s" type.', \gettype($this->data)));
219
        }
220
221
        $this->data += $step;
222
223
        return $this;
224
    }
225
226
    /**
227
     * @throws PhpfastcacheInvalidTypeException
228
     */
229
    public function decrement(int $step = 1): ExtendedCacheItemInterface
230
    {
231
        if ($this->data !== null && !\is_numeric($this->data)) {
232
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot decrement on a "%s" type.', \gettype($this->data)));
233
        }
234
235
        $this->data -= $step;
236
237
        return $this;
238
    }
239
240
    /**
241
     * @throws PhpfastcacheInvalidTypeException
242
     */
243
    public function append(array|string $data): ExtendedCacheItemInterface
244
    {
245
        if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
246
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot append on a "%s" type.', \gettype($this->data)));
247
        }
248
249
        if (\is_array($this->data)) {
250
            $this->data[] = $data;
251
        } else {
252
            $this->data .= $data;
253
        }
254
255
        return $this;
256
    }
257
258
    /**
259
     * @throws PhpfastcacheInvalidTypeException
260
     */
261
    public function prepend(array|string $data): ExtendedCacheItemInterface
262
    {
263
        if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
264
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot prepend on a "%s" type.', \gettype($this->data)));
265
        }
266
267
        if (\is_array($this->data)) {
268
            \array_unshift($this->data, $data);
269
        } else {
270
            $this->data = $data . $this->data;
271
        }
272
273
        return $this;
274
    }
275
276
    /**
277
     * Return the data as a well-formatted string.
278
     * Any scalar value will be cast to an array
279
     * @param int $options \json_encode() options
280
     * @param int $depth \json_encode() depth
281
     * @return string
282
     */
283
    public function getDataAsJsonString(int $options = JSON_THROW_ON_ERROR, int $depth = 512): string
284
    {
285
        $data = $this->get();
286
287
        if (\is_object($data) || \is_array($data)) {
288
            $data = \json_encode($data, $options, $depth);
289
        } else {
290
            $data = \json_encode([$data], $options, $depth);
291
        }
292
293
        return \json_encode($data, $options, $depth);
294
    }
295
296
    public function jsonSerialize(): mixed
297
    {
298
        return $this->get();
299
    }
300
301
    public function doesItemBelongToThatDriverBackend(ExtendedCacheItemPoolInterface $driverPool): bool
302
    {
303
        return $driverPool::getClassNamespace() === self::getClassNamespace();
304
    }
305
306
    abstract protected function getDriverClass(): string;
307
}
308