KeyPairFormatValidationTrait   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validatePublicKeyFormat() 0 12 5
A validatePrivateKeyFormat() 0 12 5
1
<?php
2
3
/**
4
 * Trait implementation of asymmetric key pair format validation methods.
5
 */
6
7
namespace CryptoManana\Core\Traits\CommonValidations;
8
9
/**
10
 * Trait KeyPairFormatValidationTrait - Reusable implementation of asymmetric key pair format validations.
11
 *
12
 * @package CryptoManana\Core\Traits\CommonValidations
13
 */
14
trait KeyPairFormatValidationTrait
15
{
16
    /**
17
     * Internal method for the validation of the private key string representation format.
18
     *
19
     * @param string $privateKey The private key input string.
20
     *
21
     * @throws \Exception Validation errors.
22
     *
23
     * @note The parameter is passed via reference from the main logical method for performance reasons.
24
     */
25 316
    protected function validatePrivateKeyFormat(&$privateKey)
26
    {
27 316
        if (!is_string($privateKey)) {
28 8
            throw new \InvalidArgumentException('The private key must be a string or a binary string.');
29
        }
30
31 316
        $isPrivateBase64String = (
32 316
            !empty($privateKey) && preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $privateKey) && strlen($privateKey) % 4 === 0
33 316
        );
34
35 316
        if (!$isPrivateBase64String) {
36 10
            throw new \InvalidArgumentException('The private key must be a valid Base64 formatted string.');
37
        }
38
    }
39
40
    /**
41
     * Internal method for the validation of the public key string representation format.
42
     *
43
     * @param string $publicKey The public key input string.
44
     *
45
     * @throws \Exception Validation errors.
46
     *
47
     * @note The parameter is passed via reference from the main logical method for performance reasons.
48
     */
49 314
    protected function validatePublicKeyFormat(&$publicKey)
50
    {
51 314
        if (!is_string($publicKey)) {
52 8
            throw new \InvalidArgumentException('The public key must be a string or a binary string.');
53
        }
54
55 314
        $isPublicBase64String = (
56 314
            !empty($publicKey) && preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $publicKey) && strlen($publicKey) % 4 === 0
57 314
        );
58
59 314
        if (!$isPublicBase64String) {
60 10
            throw new \InvalidArgumentException('The public key must be a valid Base64 formatted string.');
61
        }
62
    }
63
}
64