-
Notifications
You must be signed in to change notification settings - Fork 0
/
ItemDecorator.php
109 lines (88 loc) · 2.19 KB
/
ItemDecorator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Jsq\CacheEncryption;
use Psr\Cache\CacheItemInterface;
abstract class ItemDecorator implements CacheItemInterface
{
/** @var string */
private $cipher;
/** @var mixed */
private $decrypted;
/** @var CacheItemInterface */
private $decorated;
public function __construct($cipher, CacheItemInterface $decorated)
{
$this->cipher = $cipher;
$this->decorated = $decorated;
}
public function getKey()
{
return $this->decorated->getKey();
}
/**
* @return CacheItemInterface
*/
public function getDecorated()
{
return $this->decorated;
}
public function set($value)
{
$this->decorated->set($this->encrypt($value));
$this->decrypted = $value;
return $this;
}
public function get()
{
if (empty($this->decrypted) && $this->isHit()) {
$this->decrypted = $this->decrypt($this->getDecorated()->get());
}
return $this->decrypted;
}
public function isHit()
{
return $this->decorated->isHit()
&& $this->isDecryptable();
}
public function expiresAt($expiresAt)
{
$this->decorated->expiresAt($expiresAt);
return $this;
}
public function expiresAfter($expiresAfter)
{
$this->decorated->expiresAfter($expiresAfter);
return $this;
}
protected function generateIv()
{
return random_bytes(openssl_cipher_iv_length($this->cipher));
}
protected function encryptString($string, $key, $iv)
{
return openssl_encrypt($string, $this->cipher, $key, 0, $iv);
}
protected function decryptString($string, $method, $key, $iv)
{
return openssl_decrypt($string, $method, $key, 0, $iv);
}
protected function getCipherMethod()
{
return $this->cipher;
}
/**
* @param $data
*
* @return EncryptedValue
*/
abstract protected function encrypt($data);
/**
* @param EncryptedValue $data
*
* @return mixed
*/
abstract protected function decrypt($data);
/**
* @return bool
*/
abstract protected function isDecryptable();
}