ItemDecorator::encryptString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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