Cypher::encodeMailMessage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Da\Mailer\Security;
4
5
use Da\Mailer\Model\MailMessage;
6
use phpseclib3\Crypt\AES;
7
8
final class Cypher implements CypherInterface
9
{
10
    /**
11
     * @var AES strategy
12
     */
13
    private $strategy;
14
/**
15
     * @var string the key to encode/decode
16
     */
17
    private $key;
18
/**
19
     * Cipher constructor.
20
     *
21
     * @param $key
22
     */
23
    public function __construct($key, $iv)
24 2
    {
25
        $this->key = $key;
26 2
        $this->iv = $iv;
0 ignored issues
show
Bug Best Practice introduced by
The property iv does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
27
// initialize cypher with strongest mode and with AES. Is an anti-pattern and should be passed through the
28
        // constructor as an argument, but this way we ensure the library does have the strongest strategy by default.
29 2
        $this->strategy = new AES('cbc');
30
        $this->strategy->setKeyLength(256);
31 2
    }
32 2
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function encodeMailMessage(MailMessage $mailMessage)
37 2
    {
38
        $jsonEncodedMailMessage = json_encode($mailMessage, JSON_NUMERIC_CHECK);
39 2
        $this->strategy->setKey($this->key);
40 2
        $this->strategy->setIV($this->iv);
41
        return base64_encode($this->strategy->encrypt($jsonEncodedMailMessage));
42 2
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function decodeMailMessage($encodedMailMessage)
48 2
    {
49
        $this->strategy->setKey($this->key);
50 2
        $decryptedMailMessage = $this->strategy->decrypt(base64_decode($encodedMailMessage, true));
51 2
        $jsonDecodedMailMessageAttributes = json_decode($decryptedMailMessage, true);
52 2
        return new MailMessage($jsonDecodedMailMessageAttributes);
53
    }
54
}
55