JsonEncrypter   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 50
rs 10
c 0
b 0
f 0
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A fromJson() 0 11 3
A asJson() 0 7 2
A decryptAsObject() 0 5 1
A __construct() 0 5 1
A decrypt() 0 3 1
A encrypt() 0 3 1
1
<?php
2
3
namespace Endeavors\Components\Encryption;
4
5
use Endeavors\Components\Encryption\Contracts\IEncrypter;
6
use Endeavors\Components\Encryption\Contracts\IOriginalEncrypter;
7
use Endeavors\Components\Encryption\Contracts\IJsonDecrypter;
8
9
class JsonEncrypter implements IJsonDecrypter
10
{
11
    private $encrypter;
12
13
    private $decryptAsObject;
14
15
    public function __construct(IOriginalEncrypter $encrypter, $decryptAsObject = false)
16
    {
17
        $this->encrypter = $encrypter;
18
19
        $this->decryptAsObject = $decryptAsObject;
20
    }
21
22
    public function encrypt($value)
23
    {
24
        return $this->encrypter->encrypt($this->asJson($value), false);
25
    }
26
27
    public function decrypt(string $value)
28
    {
29
        return $this->fromJson($this->encrypter->decrypt($value, false));
30
    }
31
32
    public function decryptAsObject()
33
    {
34
        $this->decryptAsObject = true;
35
36
        return new static($this->encrypter, $this->decryptAsObject);
37
    }
38
39
    protected function asJson($value)
40
    {
41
        if (!is_string($value)) {
42
            return json_encode($value);
43
        }
44
45
        return $value;
46
    }
47
48
    protected function fromJson($value)
49
    {
50
        if (null === json_decode($value)) {
51
            return $value;
52
        }
53
54
        if ($this->decryptAsObject) {
55
            return json_decode($value);
56
        }
57
58
        return json_decode($value, true);
59
    }
60
}