CryptTrait   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 77.78%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 51
ccs 14
cts 18
cp 0.7778
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A decrypt() 0 14 4
A setEncryptionKey() 0 3 1
A encrypt() 0 14 4
1
<?php
2
3
/**
4
 * Encrypt/decrypt with encryptionKey.
5
 *
6
 * @author      Alex Bilbie <[email protected]>
7
 * @copyright   Copyright (c) Alex Bilbie
8
 * @license     http://mit-license.org/
9
 *
10
 * @link        https://github.com/thephpleague/oauth2-server
11
 */
12
13
declare(strict_types=1);
14
15
namespace League\OAuth2\Server;
16
17
use Defuse\Crypto\Crypto;
18
use Defuse\Crypto\Key;
19
use Exception;
20
use LogicException;
21
22
use function is_string;
23
24
trait CryptTrait
25
{
26
    protected string|Key|null $encryptionKey = null;
27
28
    /**
29
     * Encrypt data with encryptionKey.
30
     *
31
     * @throws LogicException
32
     */
33 48
    protected function encrypt(string $unencryptedData): string
34
    {
35
        try {
36 48
            if ($this->encryptionKey instanceof Key) {
37 1
                return Crypto::encrypt($unencryptedData, $this->encryptionKey);
38
            }
39
40 47
            if (is_string($this->encryptionKey)) {
41 47
                return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
42
            }
43
44
            throw new LogicException('Encryption key not set when attempting to encrypt');
45
        } catch (Exception $e) {
46
            throw new LogicException($e->getMessage(), 0, $e);
47
        }
48
    }
49
50
    /**
51
     * Decrypt data with encryptionKey.
52
     *
53
     * @throws LogicException
54
     */
55 35
    protected function decrypt(string $encryptedData): string
56
    {
57
        try {
58 35
            if ($this->encryptionKey instanceof Key) {
59 1
                return Crypto::decrypt($encryptedData, $this->encryptionKey);
60
            }
61
62 34
            if (is_string($this->encryptionKey)) {
63 34
                return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
64
            }
65
66
            throw new LogicException('Encryption key not set when attempting to decrypt');
67 2
        } catch (Exception $e) {
68 2
            throw new LogicException($e->getMessage(), 0, $e);
69
        }
70
    }
71
72 114
    public function setEncryptionKey(Key|string|null $key = null): void
73
    {
74 114
        $this->encryptionKey = $key;
75
    }
76
}
77