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

CryptographyService::encrypt()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
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