Passed
Pull Request — master (#838)
by Georges
03:44 queued 01:36
created

ExtendedCacheItemTrait::getExpirationDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
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
declare(strict_types=1);
15
16
namespace Phpfastcache\Core\Item;
17
18
use DateTime;
19
use DateTimeInterface;
20
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
21
use Phpfastcache\Event\EventManagerInterface;
22
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
23
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
24
25
trait ExtendedCacheItemTrait
26
{
27
    use CacheItemTrait;
28
29
    protected ExtendedCacheItemPoolInterface $driver;
30
31
    protected string $encodedKey;
32
33
    /**
34
     * Item constructor.
35
     * @param ExtendedCacheItemPoolInterface $driver
36
     * @param string $key
37
     * @param EventManagerInterface $em
38
     * @throws PhpfastcacheInvalidArgumentException
39
     */
40
    public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em)
41
    {
42
        $this->data = null;
43
        $this->key = $key;
44
        $this->setEventManager($em);
45
        $this->setDriver($driver);
46
        if ($driver->getConfig()->isUseStaticItemCaching()) {
47
            $this->driver->setItem($this);
1 ignored issue
show
Bug introduced by
$this of type Phpfastcache\Core\Item\ExtendedCacheItemTrait is incompatible with the type Psr\Cache\CacheItemInterface expected by parameter $item of Phpfastcache\Core\Pool\E...oolInterface::setItem(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

47
            $this->driver->setItem(/** @scrutinizer ignore-type */ $this);
Loading history...
48
        }
49
        $this->expirationDate = new DateTime();
50
        if ($this->driver->getConfig()->isItemDetailedDate()) {
51
            $this->creationDate = new DateTime();
52
            $this->modificationDate = new DateTime();
53
        }
54
    }
55
56
    /**
57
     * @param ExtendedCacheItemPoolInterface $driver
58
     * @return ExtendedCacheItemInterface
59
     * @throws PhpfastcacheInvalidArgumentException
60
     */
61
    public function setDriver(ExtendedCacheItemPoolInterface $driver): ExtendedCacheItemInterface
62
    {
63
        $driverClass = $this->getDriverClass();
64
        if ($driver instanceof $driverClass) {
65
            $this->driver = $driver;
66
67
            return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
68
        }
69
70
        throw new PhpfastcacheInvalidArgumentException(\sprintf('Invalid driver instance "%s" for cache item "%s"', $driver::class, static::class));
71
    }
72
73
    /**
74
     * @inheritDoc
75
     */
76
    public function getEncodedKey(): string
77
    {
78
        // Only calculate the encoded key on demand to save resources
79
        if (!isset($this->encodedKey)) {
80
            $keyHashFunction = $this->driver->getConfig()->getDefaultKeyHashFunction();
81
82
            if ($keyHashFunction) {
83
                $this->encodedKey = $keyHashFunction($this->getKey());
84
            } else {
85
                $this->encodedKey = $this->getKey();
86
            }
87
        }
88
89
        return $this->encodedKey;
90
    }
91
92
    /**
93
     * @inheritDoc
94
     */
95
    public function getRawValue(): mixed
96
    {
97
        return $this->data;
98
    }
99
100
    /**
101
     * @inheritDoc
102
     */
103
    public function getExpirationDate(): DateTimeInterface
104
    {
105
        return $this->expirationDate;
106
    }
107
108
    /**
109
     * @inheritDoc
110
     * @throws PhpfastcacheInvalidArgumentException
111
     */
112
    public function setExpirationDate(DateTimeInterface $expiration): ExtendedCacheItemInterface
113
    {
114
        return $this->expiresAt($expiration);
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this->expiresAt($expiration) returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
115
    }
116
117
    /**
118
     * @inheritDoc
119
     * @throws PhpfastcacheLogicException
120
     */
121
    public function getCreationDate(): DateTimeInterface
122
    {
123
        if ($this->driver->getConfig()->isItemDetailedDate()) {
124
            return $this->creationDate;
125
        }
126
127
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
128
    }
129
130
    /**
131
     * @inheritDoc
132
     * @throws PhpfastcacheLogicException
133
     */
134
    public function setCreationDate(DateTimeInterface $date): ExtendedCacheItemInterface
135
    {
136
        if ($this->driver->getConfig()->isItemDetailedDate()) {
137
            $this->creationDate = $date;
138
            return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
139
        }
140
141
        throw new PhpfastcacheLogicException('Cannot access to the creation date when the "itemDetailedDate" configuration is disabled.');
142
    }
143
144
    /**
145
     * @inheritDoc
146
     * @throws PhpfastcacheLogicException
147
     */
148
    public function getModificationDate(): DateTimeInterface
149
    {
150
        if ($this->driver->getConfig()->isItemDetailedDate()) {
151
            return $this->modificationDate;
152
        }
153
154
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
155
    }
156
157
    /**
158
     * @inheritDoc
159
     * @throws PhpfastcacheLogicException
160
     */
161
    public function setModificationDate(DateTimeInterface $date): ExtendedCacheItemInterface
162
    {
163
        if ($this->driver->getConfig()->isItemDetailedDate()) {
164
            $this->modificationDate = $date;
165
            return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
166
        }
167
168
        throw new PhpfastcacheLogicException('Cannot access to the modification date when the "itemDetailedDate" configuration is disabled.');
169
    }
170
171
    public function getTtl(): int
172
    {
173
        return \max(0, $this->expirationDate->getTimestamp() - \time());
174
    }
175
176
    public function isExpired(): bool
177
    {
178
        return $this->expirationDate->getTimestamp() < (new DateTime())->getTimestamp();
179
    }
180
181
    public function isNull(): bool
182
    {
183
        return $this->data === null;
184
    }
185
186
    public function isEmpty(): bool
187
    {
188
        return empty($this->data);
189
    }
190
191
    /**
192
     * Return the data length:
193
     * Either the string length if it's a string (binary mode)
194
     * # or the number of element (count) if it's an array
195
     * # or the number returned by count() if it's an object implementing \Countable interface
196
     * # -1 for anything else
197
     * @return int
198
     */
199
    public function getLength(): int
200
    {
201
        switch (\gettype($this->data)) {
202
            case 'array':
203
            case 'object':
204
                if (\is_countable($this->data)) {
205
                    return \count($this->data);
206
                }
207
                break;
208
209
            case 'string':
210
                return \strlen($this->data);
211
        }
212
213
        return -1;
214
    }
215
216
    public function increment(int $step = 1): ExtendedCacheItemInterface
217
    {
218
        $this->data += $step;
219
220
        return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
221
    }
222
223
    public function decrement(int $step = 1): ExtendedCacheItemInterface
224
    {
225
        $this->data -= $step;
226
227
        return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
228
    }
229
230
    public function append(array|string $data): ExtendedCacheItemInterface
231
    {
232
        if (\is_array($this->data)) {
233
            $this->data[] = $data;
234
        } else {
235
            $this->data .= $data;
236
        }
237
238
        return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
239
    }
240
241
    public function prepend(array|string $data): ExtendedCacheItemInterface
242
    {
243
        if (\is_array($this->data)) {
244
            \array_unshift($this->data, $data);
245
        } else {
246
            $this->data = $data . $this->data;
1 ignored issue
show
Bug introduced by
Are you sure $data of type array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
            $this->data = /** @scrutinizer ignore-type */ $data . $this->data;
Loading history...
247
        }
248
249
        return $this;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this returns the type Phpfastcache\Core\Item\ExtendedCacheItemTrait which is incompatible with the type-hinted return Phpfastcache\Core\Item\ExtendedCacheItemInterface.
Loading history...
250
    }
251
252
    /**
253
     * Return the data as a well-formatted string.
254
     * Any scalar value will be casted to an array
255
     * @param int $options \json_encode() options
256
     * @param int $depth \json_encode() depth
257
     * @return string
258
     */
259
    public function getDataAsJsonString(int $options = JSON_THROW_ON_ERROR, int $depth = 512): string
260
    {
261
        $data = $this->get();
262
263
        if (\is_object($data) || \is_array($data)) {
264
            $data = \json_encode($data, $options, $depth);
265
        } else {
266
            $data = \json_encode([$data], $options, $depth);
267
        }
268
269
        return \json_encode($data, $options, $depth);
270
    }
271
272
    public function jsonSerialize(): mixed
273
    {
274
        return $this->get();
275
    }
276
277
    public function doesItemBelongToThatDriverBackend(ExtendedCacheItemPoolInterface $driverPool): bool
278
    {
279
        return $driverPool::getClassNamespace() === self::getClassNamespace();
280
    }
281
282
    /**
283
     * @throws PhpfastcacheLogicException
284
     * @throws PhpfastcacheInvalidArgumentException
285
     */
286
    public function cloneInto(ExtendedCacheItemInterface $itemTarget, ?ExtendedCacheItemPoolInterface $itemPoolTarget = null): void
287
    {
288
        $itemTarget->setEventManager($this->getEventManager())
289
            ->set($this->getRawValue())
290
            ->setHit($this->isHit())
291
            ->setTags($this->getTags())
0 ignored issues
show
Bug introduced by
It seems like getTags() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

291
            ->setTags($this->/** @scrutinizer ignore-call */ getTags())
Loading history...
292
            ->expiresAt($this->getExpirationDate())
293
            ->setDriver($itemPoolTarget ?? $this->driver);
294
295
        if ($this->driver->getConfig()->isItemDetailedDate()) {
296
            $itemTarget->setCreationDate($this->getCreationDate())
297
                ->setModificationDate($this->getModificationDate());
298
        }
299
    }
300
301
    abstract protected function getDriverClass(): string;
302
}
303