Completed
Push — master ( c39607...87b4fe )
by Jonathan
09:41
created

ItemDecorator::decryptString()   A

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