Completed
Push — master ( 604a9a...cf79ad )
by Tony Karavasilev (Тони
18:44
created

validatePrivateKeyFormat()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.6111
cc 5
nc 7
nop 1
crap 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
     * @internal The parameter is passed via reference from the main logical method for performance reasons.
24
     */
25 568
    protected function validatePrivateKeyFormat(&$privateKey)
26
    {
27 568
        if (!is_string($privateKey)) {
28 16
            throw new \InvalidArgumentException('The private key must be a string or a binary string.');
29
        }
30
31
        $isPrivateBase64String = (
32 568
            !empty($privateKey) && preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $privateKey) && strlen($privateKey) % 4 === 0
33
        );
34
35 568
        if (!$isPrivateBase64String) {
36 16
            throw new \InvalidArgumentException('The private key must be a valid Base64 formatted string.');
37
        }
38 568
    }
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
     * @internal The parameter is passed via reference from the main logical method for performance reasons.
48
     */
49 560
    protected function validatePublicKeyFormat(&$publicKey)
50
    {
51 560
        if (!is_string($publicKey)) {
52 16
            throw new \InvalidArgumentException('The public key must be a string or a binary string.');
53
        }
54
55
        $isPublicBase64String = (
56 560
            !empty($publicKey) && preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $publicKey) && strlen($publicKey) % 4 === 0
57
        );
58
59 560
        if (!$isPublicBase64String) {
60 16
            throw new \InvalidArgumentException('The public key must be a valid Base64 formatted string.');
61
        }
62 560
    }
63
}
64