Completed
Pull Request — master (#1)
by Jonathan
04:04
created

ItemDecorator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
c 1
b 0
f 1
lcom 1
cbo 4
dl 0
loc 54
ccs 24
cts 24
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A get() 0 8 2
A isDecryptable() 0 6 1
A encrypt() 0 4 1
A setTokenFromDecorated() 0 13 3
1
<?php
2
namespace Jsq\CacheEncryption\Iron;
3
4
use Jsq\CacheEncryption\ItemDecorator as BaseItemDecorator;
5
use Jsq\Iron\Iron;
6
use Jsq\Iron\PasswordInterface;
7
use Jsq\Iron\Token;
8
use Psr\Cache\CacheItemInterface;
9
10
class ItemDecorator extends BaseItemDecorator
11
{
12
    /** @var PasswordInterface */
13
    private $password;
14
    /** @var Iron */
15
    private $iron;
16
    /** @var Token|null */
17
    private $token;
18
19 147
    public function __construct(
20
        CacheItemInterface $decorated,
21
        PasswordInterface $password,
22
        $cipher
23
    ) {
24 147
        parent::__construct($decorated);
25 147
        $this->password = $password;
26 147
        $this->iron = new Iron($cipher);
27 147
    }
28
29 75
    public function get()
30
    {
31 75
        $this->setTokenFromDecorated();
32
33 75
        return isset($this->token)
34 75
            ? $this->iron->decryptToken($this->token, $this->password)
35 75
            : null;
36
    }
37
38 48
    protected function isDecryptable()
39
    {
40 48
        $this->setTokenFromDecorated();
41
42 48
        return isset($this->token);
43
    }
44
45 102
    protected function encrypt($data)
46
    {
47 102
        return (string) $this->iron->encrypt($this->password, $data);
48
    }
49
50 117
    private function setTokenFromDecorated()
51
    {
52 117
        if (empty($this->token)) {
53
            try {
54 117
                $this->token = Token::fromSealed(
55 117
                    $this->password,
56 117
                    $this->getDecorated()->get()
57 117
                );
58 117
            } catch (\Exception $e) {
59
                // not a valid token!
60
            }
61 117
        }
62 117
    }
63
}
64