Passed
Push — main ( 5ea0b1...8c9564 )
by Fractal
12:58
created

CryptographyService   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A encrypt() 0 9 3
A decrypt() 0 10 5
A isEncrypted() 0 3 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FRZB\Component\Cryptography\Service;
6
7
use FRZB\Component\Cryptography\Exception\CryptographyException;
8
use phpseclib\Crypt\Base as Crypto;
9
10
class CryptographyService implements CryptographyInterface
11
{
12 11
    public function __construct(
13
        private readonly Crypto $crypto,
14
    ) {
15 11
    }
16
17 8
    public function isEncrypted(string $payload): bool
18
    {
19 8
        return str_starts_with($payload, '<ENC>') && str_ends_with($payload, '</ENC>');
20
    }
21
22 9
    public function encrypt(string $payload): string
23
    {
24
        try {
25 9
            $encrypted = (string) ($this->crypto->encrypt($payload) ?: throw CryptographyException::encryptFailure());
26 2
        } catch (\Throwable $e) {
27 2
            throw CryptographyException::fromThrowable($e);
28
        }
29
30 7
        return sprintf('<ENC>%s</ENC>', base64_encode($encrypted));
31
    }
32
33 6
    public function decrypt(string $payload): string
34
    {
35 6
        $this->isEncrypted($payload) ?: throw CryptographyException::notEncrypted();
36 5
        $payload = str_replace(['<ENC>', '</ENC>'], ['', ''], $payload);
37 5
        $payload = (string) (base64_decode($payload, true) ?: throw CryptographyException::decodeFailure());
38
39
        try {
40 4
            return (string) ($this->crypto->decrypt($payload) ?: throw CryptographyException::decryptFailure());
41 1
        } catch (\Throwable $e) {
42 1
            throw CryptographyException::fromThrowable($e);
43
        }
44
    }
45
}
46