1
|
|
|
<?php |
2
|
|
|
namespace Fwlib\Cache; |
3
|
|
|
|
4
|
|
|
use Fwlib\Config\ConfigAwareTrait; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Shared code of cache handlers |
8
|
|
|
* |
9
|
|
|
* @property string $emptyKeyReplacement |
10
|
|
|
* @property string $hashAlgorithm |
11
|
|
|
* |
12
|
|
|
* @copyright Copyright 2012-2015 Fwolf |
13
|
|
|
* @license http://www.gnu.org/licenses/lgpl.html LGPL-3.0+ |
14
|
|
|
*/ |
15
|
|
|
trait HandlerTrait |
16
|
|
|
{ |
17
|
|
|
use ConfigAwareTrait; |
18
|
|
|
use LoggerAwareTrait; |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Compute expiration timestamp |
23
|
|
|
* |
24
|
|
|
* @param int $lifetime Length, in seconds |
25
|
|
|
* @param int $startTime Start timestamp, default use time() |
26
|
|
|
* @return int End timestamp or 0 for never expire |
27
|
|
|
*/ |
28
|
|
|
protected function computeExpireTime($lifetime = null, $startTime = 0) |
29
|
|
|
{ |
30
|
|
|
// If not set, read lifetime from config |
31
|
|
|
if (is_null($lifetime)) { |
32
|
|
|
$lifetime = $this->getLifetime(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// 0 means never expire |
36
|
|
|
if (0 == $lifetime) { |
37
|
|
|
return 0; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (0 == $startTime) { |
41
|
|
|
$startTime = time(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $startTime + $lifetime; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Get lifetime length, in seconds |
50
|
|
|
* |
51
|
|
|
* For solid lifetime length, define them in configs. |
52
|
|
|
* For dynamic lifetime length, overwrite this method to compute it. |
53
|
|
|
* |
54
|
|
|
* This implement will return 0 if config not set, means never expire. |
55
|
|
|
* |
56
|
|
|
* @param string $key |
57
|
|
|
* @return int |
58
|
|
|
*/ |
59
|
|
|
protected function getLifetime($key = null) |
60
|
|
|
{ |
61
|
|
|
true || $key; |
|
|
|
|
62
|
|
|
|
63
|
|
|
return $this->getConfig('lifetime', 0); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Convert required key to actual key inner used |
69
|
|
|
* |
70
|
|
|
* In some cache system, key may need manual hashed. |
71
|
|
|
* |
72
|
|
|
* @param string $key |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
|
|
protected function hashKey($key) |
76
|
|
|
{ |
77
|
|
|
$key = trim($key); |
78
|
|
|
|
79
|
|
|
// Key can not be empty |
80
|
|
|
if (empty($key)) { |
81
|
|
|
return $this->emptyKeyReplacement; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return empty($this->hashAlgorithm) |
85
|
|
|
? $key |
86
|
|
|
: hash($this->hashAlgorithm, $key); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: