1
|
|
|
<?php |
2
|
|
|
namespace Jsq\Cache\IronEncryption; |
3
|
|
|
|
4
|
|
|
use Doctrine\Common\Cache\Cache; |
5
|
|
|
use Jsq\Cache\EncryptionStatsTrait; |
6
|
|
|
use Iron; |
7
|
|
|
use Iron\PasswordInterface; |
8
|
|
|
use Iron\Token; |
9
|
|
|
use Throwable; |
10
|
|
|
|
11
|
|
|
class Decorator implements Cache |
12
|
|
|
{ |
13
|
|
|
use EncryptionStatsTrait; |
14
|
|
|
|
15
|
|
|
/** @var Cache */ |
16
|
|
|
private $decorated; |
17
|
|
|
/** @var Iron\Iron */ |
18
|
|
|
private $iron; |
19
|
|
|
/** @var PasswordInterface */ |
20
|
|
|
private $password; |
21
|
|
|
|
22
|
|
|
public function __construct( |
23
|
|
|
Cache $decorated, |
24
|
|
|
$password, |
25
|
|
|
$cipher = Iron\Iron::DEFAULT_ENCRYPTION_METHOD |
26
|
|
|
) { |
27
|
|
|
if (!class_exists(Iron\Iron::class)) { |
28
|
|
|
// @codeCoverageIgnoreStart |
29
|
|
|
throw new \RuntimeException('You must install' |
30
|
|
|
. ' jsq/iron-php to use the Iron decorator.'); |
31
|
|
|
// @codeCoverageIgnoreEnd |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$this->decorated = $decorated; |
35
|
|
|
$this->password = Iron\normalize_password($password); |
36
|
|
|
$this->iron = new Iron\Iron($cipher); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function fetch($id) |
40
|
|
|
{ |
41
|
|
|
try { |
42
|
|
|
return $this->returnHit($this->callAndTime(function () use ($id) { |
43
|
|
|
return json_decode($this->iron->decryptToken( |
44
|
|
|
Token::fromSealed( |
45
|
|
|
$this->password, |
46
|
|
|
$this->decorated->fetch($id) |
47
|
|
|
), |
48
|
|
|
$this->password |
49
|
|
|
), true); |
50
|
|
|
})); |
51
|
|
|
} catch (Throwable $e) { |
52
|
|
|
return $this->returnMiss(false); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function contains($id) |
57
|
|
|
{ |
58
|
|
|
try { |
59
|
|
|
Token::fromSealed( |
60
|
|
|
$this->password, |
61
|
|
|
$this->decorated->fetch($id) |
62
|
|
|
); |
63
|
|
|
return true; |
64
|
|
|
} catch (Throwable $e) { |
65
|
|
|
return false; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function save($id, $data, $ttl = 0) |
70
|
|
|
{ |
71
|
|
|
return $this->decorated->save( |
72
|
|
|
$id, |
73
|
|
|
(string) $this->callAndTime(function () use ($data, $ttl) { |
74
|
|
|
return $this->iron |
75
|
|
|
->encrypt($this->password, json_encode($data), $ttl); |
76
|
|
|
}), |
77
|
|
|
$ttl |
78
|
|
|
); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function delete($id) |
82
|
|
|
{ |
83
|
|
|
return $this->decorated->delete($id); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
public function getStats() |
87
|
|
|
{ |
88
|
|
|
return $this->getEncryptionStats($this->decorated->getStats() ?: []); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|