Completed
Pull Request — final (#444)
by
unknown
02:12
created

ItemBaseTrait::touch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 9.4285
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache\Cache;
16
17
use phpFastCache\Core\DriverAbstract;
18
19
trait ItemBaseTrait
20
{
21
    /**
22
     * @var bool
23
     */
24
    protected $fetched = false;
25
26
    /**
27
     * @var DriverAbstract
28
     */
29
    protected $driver;
30
31
    /**
32
     * @var string
33
     */
34
    protected $key;
35
36
    /**
37
     * @var mixed
38
     */
39
    protected $data;
40
41
    /**
42
     * @var \DateTime
43
     */
44
    protected $expirationDate;
45
46
    /**
47
     * @var array
48
     */
49
    protected $tags = [];
50
51
    /**
52
     * @var array
53
     */
54
    protected $removedTags = [];
55
56
    /**
57
     * @var bool
58
     */
59
    protected $isHit = false;
60
61
    /********************
62
     *
63
     * PSR-6 Methods
64
     *
65
     *******************/
66
67
    /**
68
     * @return string
69
     */
70
    public function getKey()
71
    {
72
        return $this->key;
73
    }
74
75
    /**
76
     * @return mixed
77
     */
78
    public function get()
79
    {
80
        return $this->data;
81
    }
82
83
    /**
84
     * @param mixed $value
85
     * @return $this
86
     */
87
    public function set($value)
88
    {
89
        /**
90
         * The user set a value,
91
         * therefore there is no need to
92
         * fetch from source anymore
93
         */
94
        $this->fetched = true;
95
        $this->data = $value;
96
97
        return $this;
98
    }
99
100
    /**
101
     * @return bool
102
     * @throws \InvalidArgumentException
103
     */
104
    public function isHit()
105
    {
106
        return $this->isHit;
107
    }
108
109
    /**
110
     * @param bool $isHit
111
     * @return $this
112
     * @throws \InvalidArgumentException
113
     */
114
    public function setHit($isHit)
115
    {
116
        if (is_bool($isHit)) {
117
            $this->isHit = $isHit;
118
119
            return $this;
120
        } else {
121
            throw new \InvalidArgumentException('$isHit must be a boolean');
122
        }
123
    }
124
125
    /**
126
     * @param \DateTimeInterface $expiration
127
     * @return $this
128
     */
129
    public function expiresAt($expiration)
130
    {
131
        $_php_ver = (float) PHP_VERSION;
132
		if ($_php_ver >= 5.5) {
133
		    
134
            if ($expiration instanceof \DateTimeInterface) {
135
                     $this->expirationDate = $expiration;
0 ignored issues
show
Documentation Bug introduced by
$expiration is of type object<DateTimeInterface>, but the property $expirationDate was declared to be of type object<DateTime>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
136
             } else {
137
            throw new \InvalidArgumentException('$expiration must be an object implementing the DateTimeInterface');
138
             }
139
            
140
		} else if ($_php_ver <= 5.4) {
141
			if ($expiration instanceof \DateTime) {
142
                     $this->expirationDate = $expiration;
143
             } else {
144
            throw new \InvalidArgumentException('$expiration must be an object implementing the DateTime');
145
             }
146
		} 
147
        
148
        
149
150
        return $this;
151
    }
152
153
    /**
154
     * Sets the expiration time for this cache item.
155
     *
156
     * @param int|\DateInterval $time
157
     *   The period of time from the present after which the item MUST be considered
158
     *   expired. An integer parameter is understood to be the time in seconds until
159
     *   expiration. If null is passed explicitly, a default value MAY be used.
160
     *   If none is set, the value should be stored permanently or for as long as the
161
     *   implementation allows.
162
     *
163
     * @return static
164
     *   The called object.
165
     *
166
     * @deprecated Use CacheItemInterface::expiresAfter() instead
167
     */
168
    public function touch($time)
169
    {
170
        trigger_error('touch() is deprecated and will be removed in the next major release, use CacheItemInterface::expiresAfter() instead');
171
172
        return $this->expiresAfter($time);
173
    }
174
175
    /**
176
     * @param \DateInterval|int $time
177
     * @return $this
178
     * @throws \InvalidArgumentException
179
     */
180
    public function expiresAfter($time)
181
    {
182
        if (is_numeric($time)) {
183
            if ($time <= 0) {
184
                /**
185
                 * 5 years, however memcached or memory cached will gone when u restart it
186
                 * just recommended for sqlite. files
187
                 */
188
                $time = 30 * 24 * 3600 * 5;
189
            }
190
            $this->expirationDate = (new \DateTime())->add(new \DateInterval(sprintf('PT%dS', $time)));
191
        } else if ($time instanceof \DateInterval) {
192
            $this->expirationDate = (new \DateTime())->add($time);
193
        } else {
194
            throw new \InvalidArgumentException('Invalid date format');
195
        }
196
197
        return $this;
198
    }
199
200
    /********************
201
     *
202
     * PSR-6 Extended Methods
203
     *
204
     *******************/
205
206
    /**
207
     * @return string
208
     */
209
    public function getEncodedKey()
210
    {
211
        return md5($this->getKey());
212
    }
213
214
    /**
215
     * @return mixed
216
     */
217
    public function getUncommittedData()
218
    {
219
        return $this->data;
220
    }
221
222
    /**
223
     * @return \DateTimeInterface
224
     */
225
    public function getExpirationDate()
226
    {
227
        return $this->expirationDate;
228
    }
229
230
    /**
231
     * @return int
232
     */
233
    public function getTtl()
234
    {
235
        $ttl = $this->expirationDate->getTimestamp() - time();
236
        if ($ttl > 2592000) {
237
            $ttl = time() + $ttl;
238
        }
239
240
        return $ttl;
241
    }
242
243
    /**
244
     * @return bool
245
     */
246
    public function isExpired()
247
    {
248
        return $this->expirationDate->getTimestamp() < (new \DateTime())->getTimestamp();
249
    }
250
251
    /**
252
     * @param int $step
253
     * @return $this
254
     * @throws \InvalidArgumentException
255
     */
256 View Code Duplication
    public function increment($step = 1)
257
    {
258
        if (is_int($step)) {
259
            $this->fetched = true;
260
            $this->data += $step;
261
        } else {
262
            throw new \InvalidArgumentException('$step must be numeric.');
263
        }
264
265
        return $this;
266
    }
267
268
    /**
269
     * @param int $step
270
     * @return $this
271
     * @throws \InvalidArgumentException
272
     */
273 View Code Duplication
    public function decrement($step = 1)
274
    {
275
        if (is_int($step)) {
276
            $this->fetched = true;
277
            $this->data -= $step;
278
        } else {
279
            throw new \InvalidArgumentException('$step must be numeric.');
280
        }
281
282
        return $this;
283
    }
284
285
    /**
286
     * @param array|string $data
287
     * @return $this
288
     * @throws \InvalidArgumentException
289
     */
290 View Code Duplication
    public function append($data)
291
    {
292
        if (is_array($this->data)) {
293
            array_push($this->data, $data);
294
        } else if (is_string($data)) {
295
            $this->data .= (string) $data;
296
        } else {
297
            throw new \InvalidArgumentException('$data must be either array nor string.');
298
        }
299
300
        return $this;
301
    }
302
303
304
    /**
305
     * @param array|string $data
306
     * @return $this
307
     * @throws \InvalidArgumentException
308
     */
309 View Code Duplication
    public function prepend($data)
310
    {
311
        if (is_array($this->data)) {
312
            array_unshift($this->data, $data);
313
        } else if (is_string($data)) {
314
            $this->data = (string) $data . $this->data;
315
        } else {
316
            throw new \InvalidArgumentException('$data must be either array nor string.');
317
        }
318
319
        return $this;
320
    }
321
322
    /**
323
     * @param $tagName
324
     * @return $this
325
     * @throws \InvalidArgumentException
326
     */
327
    public function addTag($tagName)
328
    {
329
        if (is_string($tagName)) {
330
            $this->tags = array_unique(array_merge($this->tags, [$tagName]));
331
332
            return $this;
333
        } else {
334
            throw new \InvalidArgumentException('$tagName must be a string');
335
        }
336
    }
337
338
    /**
339
     * @param array $tagNames
340
     * @return $this
341
     */
342
    public function addTags(array $tagNames)
343
    {
344
        foreach ($tagNames as $tagName) {
345
            $this->addTag($tagName);
346
        }
347
348
        return $this;
349
    }
350
351
    /**
352
     * @param array $tags
353
     * @return $this
354
     * @throws \InvalidArgumentException
355
     */
356
    public function setTags(array $tags)
357
    {
358
        if (count($tags)) {
359
            if (array_filter($tags, 'is_string')) {
360
                $this->tags = $tags;
361
            } else {
362
                throw new \InvalidArgumentException('$tagName must be an array of string');
363
            }
364
        }
365
366
        return $this;
367
    }
368
369
    /**
370
     * @return array
371
     */
372
    public function getTags()
373
    {
374
        return $this->tags;
375
    }
376
377
    /**
378
     * @return string
379
     */
380
    public function getTagsAsString($separator = ', ')
381
    {
382
        return implode($separator, $this->tags);
383
    }
384
385
    /**
386
     * @param $tagName
387
     * @return $this
388
     */
389
    public function removeTag($tagName)
390
    {
391
        if (($key = array_search($tagName, $this->tags)) !== false) {
392
            unset($this->tags[ $key ]);
393
            $this->removedTags[] = $tagName;
394
        }
395
396
        return $this;
397
    }
398
399
    /**
400
     * @param array $tagNames
401
     * @return $this
402
     */
403
    public function removeTags(array $tagNames)
404
    {
405
        foreach ($tagNames as $tagName) {
406
            $this->removeTag($tagName);
407
        }
408
409
        return $this;
410
    }
411
412
    /**
413
     * @return array
414
     */
415
    public function getRemovedTags()
416
    {
417
        return array_diff($this->removedTags, $this->tags);
418
    }
419
420
    /**
421
     * Return the data as a well-formatted string.
422
     * Any scalar value will be casted to an array
423
     * @param int $option json_encode() options
424
     * @param int $depth json_encode() depth
425
     * @return string
426
     */
427
    public function getDataAsJsonString($option = 0, $depth = 512)
428
    {
429
        $data = $this->get();
430
431
        if (is_object($data) || is_array($data)) {
432
            $data = json_encode($data, $option, $depth);
433
        } else {
434
            $data = json_encode([$data], $option, $depth);
435
        }
436
437
        return json_encode($data, $option, $depth);
438
    }
439
440
    /**
441
     * Implements \JsonSerializable interface
442
     * @return mixed
443
     */
444
    public function jsonSerialize()
445
    {
446
        return $this->get();
447
    }
448
449
    /**
450
     * Prevent recursions for Debug (php 5.6+)
451
     * @return array
452
     */
453
    final public function __debugInfo()
454
    {
455
        $info = get_object_vars($this);
456
        $info[ 'driver' ] = 'object(' . get_class($info[ 'driver' ]) . ')';
457
458
        return (array) $info;
459
    }
460
}
461