Completed
Push — master ( 517741...718c02 )
by Georges
16s queued 13s
created

ExtendedCacheItemTrait::cloneInto()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 12
rs 9.9666
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
        // Only calculate the encoded key on demand to save resources
81
        if (!isset($this->encodedKey)) {
82
            $keyHashFunction = $this->driver->getConfig()->getDefaultKeyHashFunction();
83
84
            if ($keyHashFunction) {
85
                $this->encodedKey = $keyHashFunction($this->getKey());
86
            } else {
87
                $this->encodedKey = $this->getKey();
88
            }
89
        }
90
91
        return $this->encodedKey;
92
    }
93
94
    /**
95
     * @inheritDoc
96
     */
97
    public function getRawValue(): mixed
98
    {
99
        return $this->data;
100
    }
101
102
    /**
103
     * @inheritDoc
104
     */
105
    public function getExpirationDate(): DateTimeInterface
106
    {
107
        return $this->expirationDate;
108
    }
109
110
    /**
111
     * @inheritDoc
112
     * @throws PhpfastcacheInvalidArgumentException
113
     */
114
    public function setExpirationDate(DateTimeInterface $expiration): ExtendedCacheItemInterface
115
    {
116
        return $this->expiresAt($expiration);
117
    }
118
119
    /**
120
     * @inheritDoc
121
     * @throws PhpfastcacheLogicException
122
     */
123
    public function getCreationDate(): DateTimeInterface
124
    {
125
        if ($this->driver->getConfig()->isItemDetailedDate()) {
126
            return $this->creationDate;
127
        }
128
129
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
130
    }
131
132
    /**
133
     * @inheritDoc
134
     * @throws PhpfastcacheLogicException
135
     */
136
    public function setCreationDate(DateTimeInterface $date): ExtendedCacheItemInterface
137
    {
138
        if ($this->driver->getConfig()->isItemDetailedDate()) {
139
            $this->creationDate = $this->demutateDatetime($date);
140
            return $this;
141
        }
142
143
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
144
    }
145
146
    /**
147
     * @inheritDoc
148
     * @throws PhpfastcacheLogicException
149
     */
150
    public function getModificationDate(): DateTimeInterface
151
    {
152
        if ($this->driver->getConfig()->isItemDetailedDate()) {
153
            return $this->modificationDate;
154
        }
155
156
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
157
    }
158
159
    /**
160
     * @inheritDoc
161
     * @throws PhpfastcacheLogicException
162
     */
163
    public function setModificationDate(DateTimeInterface $date): ExtendedCacheItemInterface
164
    {
165
        if ($this->driver->getConfig()->isItemDetailedDate()) {
166
            $this->modificationDate = $this->demutateDatetime($date);
167
            return $this;
168
        }
169
170
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
171
    }
172
173
    public function getTtl(): int
174
    {
175
        return \max(0, $this->expirationDate->getTimestamp() - \time());
176
    }
177
178
    public function isExpired(): bool
179
    {
180
        return $this->getTtl() <= 0;
181
    }
182
183
    public function isNull(): bool
184
    {
185
        return $this->get() === null;
186
    }
187
188
    public function isEmpty(): bool
189
    {
190
        return empty($this->get());
191
    }
192
193
    /**
194
     * Return the data length:
195
     * Either the string length if it's a string (binary mode)
196
     * # or the number of element (count) if it's an array
197
     * # or the number returned by count() if it's an object implementing \Countable interface
198
     * # -1 for anything else
199
     * @return int
200
     */
201
    public function getLength(): int
202
    {
203
        switch (\gettype($this->data)) {
204
            case 'array':
205
            case 'object':
206
                if (\is_countable($this->data)) {
207
                    return \count($this->data);
208
                }
209
                break;
210
211
            case 'string':
212
                return \strlen($this->data);
213
        }
214
215
        return -1;
216
    }
217
218
    /**
219
     * @throws PhpfastcacheInvalidTypeException
220
     */
221
    public function increment(int $step = 1): ExtendedCacheItemInterface
222
    {
223
        if ($this->data !== null && !\is_numeric($this->data)) {
224
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot increment on a "%s" type.', \gettype($this->data)));
225
        }
226
227
        $this->data += $step;
228
229
        return $this;
230
    }
231
232
    /**
233
     * @throws PhpfastcacheInvalidTypeException
234
     */
235
    public function decrement(int $step = 1): ExtendedCacheItemInterface
236
    {
237
        if ($this->data !== null && !\is_numeric($this->data)) {
238
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot decrement on a "%s" type.', \gettype($this->data)));
239
        }
240
241
        $this->data -= $step;
242
243
        return $this;
244
    }
245
246
    /**
247
     * @throws PhpfastcacheInvalidTypeException
248
     */
249
    public function append(array|string $data): ExtendedCacheItemInterface
250
    {
251
        if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
252
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot append on a "%s" type.', \gettype($this->data)));
253
        }
254
255
        if (\is_array($this->data)) {
256
            $this->data[] = $data;
257
        } else {
258
            $this->data .= $data;
259
        }
260
261
        return $this;
262
    }
263
264
    /**
265
     * @throws PhpfastcacheInvalidTypeException
266
     */
267
    public function prepend(array|string $data): ExtendedCacheItemInterface
268
    {
269
        if ($this->data !== null && !\is_string($this->data) && !\is_array($this->data)) {
270
            throw new PhpfastcacheInvalidTypeException(\sprintf('Cannot prepend on a "%s" type.', \gettype($this->data)));
271
        }
272
273
        if (\is_array($this->data)) {
274
            \array_unshift($this->data, $data);
275
        } else {
276
            $this->data = $data . $this->data;
277
        }
278
279
        return $this;
280
    }
281
282
    /**
283
     * Return the data as a well-formatted string.
284
     * Any scalar value will be casted to an array
285
     * @param int $options \json_encode() options
286
     * @param int $depth \json_encode() depth
287
     * @return string
288
     */
289
    public function getDataAsJsonString(int $options = JSON_THROW_ON_ERROR, int $depth = 512): string
290
    {
291
        $data = $this->get();
292
293
        if (\is_object($data) || \is_array($data)) {
294
            $data = \json_encode($data, $options, $depth);
295
        } else {
296
            $data = \json_encode([$data], $options, $depth);
297
        }
298
299
        return \json_encode($data, $options, $depth);
300
    }
301
302
    public function jsonSerialize(): mixed
303
    {
304
        return $this->get();
305
    }
306
307
    public function doesItemBelongToThatDriverBackend(ExtendedCacheItemPoolInterface $driverPool): bool
308
    {
309
        return $driverPool::getClassNamespace() === self::getClassNamespace();
310
    }
311
312
    abstract protected function getDriverClass(): string;
313
}
314