Completed
Push — master ( 8055c8...3e2656 )
by Tony Karavasilev (Тони
16:45
created

CipherDataFormatsTrait::getCipherFormat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * Trait implementation of the cipher/encryption data output formats for encryption algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageEncryption;
8
9
use \CryptoManana\Core\Interfaces\MessageEncryption\CipherDataFormatsInterface as CipherDataFormatsSpecification;
10
use \CryptoManana\Core\StringBuilder as StringBuilder;
11
12
/**
13
 * Trait CipherDataFormatsTrait - Reusable implementation of `CipherDataFormatsInterface`.
14
 *
15
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\CipherDataFormatsInterface The abstract specification.
16
 *
17
 * @package CryptoManana\Core\Traits\MessageEncryption
18
 *
19
 * @property int $cipherFormat The output cipher format property storage.
20
 *
21
 * @mixin CipherDataFormatsSpecification
22
 */
23
trait CipherDataFormatsTrait
24
{
25
    /**
26
     * Internal method for converting the output format representation via the chosen format.
27
     *
28
     * @param string $bytes The bytes for conversion.
29
     * @param bool|int|null $direction Flag for encryption direction (encrypt => `true` or decrypt => `false`).
30
     *
31
     * @return string The formatted bytes.
32
     */
33
    protected function changeOutputFormat($bytes, $direction = true)
34
    {
35
        if ($this->cipherFormat === self::ENCRYPTION_OUTPUT_RAW) {
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...::ENCRYPTION_OUTPUT_RAW was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
36
            return $bytes;
37
        }
38
39
        if ($direction == true) {
40
            switch ($this->cipherFormat) {
41
                case self::ENCRYPTION_OUTPUT_HEX_LOWER:
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...YPTION_OUTPUT_HEX_LOWER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
42
                    $bytes = bin2hex($bytes);
43
                    break;
44
                case self::ENCRYPTION_OUTPUT_HEX_UPPER:
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...YPTION_OUTPUT_HEX_UPPER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
45
                    $bytes = StringBuilder::stringToUpper(bin2hex($bytes));
46
                    break;
47
                case self::ENCRYPTION_OUTPUT_BASE_64:
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...CRYPTION_OUTPUT_BASE_64 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
48
                    $bytes = base64_encode($bytes);
49
                    break;
50
                case self::ENCRYPTION_OUTPUT_BASE_64_URL:
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...TION_OUTPUT_BASE_64_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
51
                default:
52
                    $bytes = base64_encode($bytes);
53
                    $bytes = StringBuilder::stringReplace(['+', '/', '='], ['-', '_', ''], $bytes);
54
                    break;
55
            }
56
        } else {
57
            $hexCasePattern = '/^[a-f0-9]+$/';
58
            $base64Pattern = '%^[a-zA-Z0-9/+]*={0,2}$%';
59
            $base64UrlFriendlyPattern = '/^[a-zA-Z0-9_-]+$/';
60
61
            switch ($this->cipherFormat) {
62
                case self::ENCRYPTION_OUTPUT_HEX_LOWER:
63
                case self::ENCRYPTION_OUTPUT_HEX_UPPER:
64
                    if (preg_match($hexCasePattern, StringBuilder::stringToLower($bytes))) {
65
                        $bytes = hex2bin(StringBuilder::stringToLower($bytes));
66
                    }
67
                    break;
68
                case self::ENCRYPTION_OUTPUT_BASE_64:
69
                    if (preg_match($base64Pattern, $bytes) && StringBuilder::stringLength($bytes) % 4 === 0) {
70
                        $bytes = base64_decode($bytes);
71
                    }
72
                    break;
73
                case self::ENCRYPTION_OUTPUT_BASE_64_URL:
74
                default:
75
                    if (preg_match($base64UrlFriendlyPattern, $bytes)) {
76
                        $bytes = StringBuilder::stringReplace(['-', '_'], ['+', '/'], $bytes);
77
                        $times = StringBuilder::stringLength($bytes) % 4;
78
79
                        // Instead of str_pad for encoding friendly appending
80
                        for ($i = 0; $i < $times; $i++) {
81
                            $bytes .= '=';
82
                        }
83
84
                        $bytes = base64_decode($bytes);
85
                    }
86
                    break;
87
            }
88
        }
89
90
        return $bytes;
91
    }
92
93
    /**
94
     * Setter for the output cipher format code property.
95
     *
96
     * @param int $cipherFormat The output cipher format code.
97
     *
98
     * @return $this The encryption algorithm object.
99
     * @throws \Exception Validation errors.
100
     */
101
    public function setCipherFormat($cipherFormat)
102
    {
103
        $cipherFormat = filter_var(
104
            $cipherFormat,
105
            FILTER_VALIDATE_INT,
106
            [
107
                "options" => [
108
                    "min_range" => self::ENCRYPTION_OUTPUT_RAW,
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...::ENCRYPTION_OUTPUT_RAW was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
109
                    "max_range" => self::ENCRYPTION_OUTPUT_BASE_64_URL,
1 ignored issue
show
Bug introduced by
The constant CryptoManana\Core\Traits...TION_OUTPUT_BASE_64_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
110
                ],
111
            ]
112
        );
113
114
        if ($cipherFormat === false) {
115
            throw new \InvalidArgumentException(
116
                'The output format mode must be an integer between ' .
117
                self::ENCRYPTION_OUTPUT_RAW . ' and ' . self::ENCRYPTION_OUTPUT_BASE_64_URL . '.'
118
            );
119
        }
120
121
        $this->cipherFormat = $cipherFormat;
122
123
        return $this;
124
    }
125
126
    /**
127
     * Getter for the output cipher format code property.
128
     *
129
     * @return int The output cipher format code.
130
     */
131
    public function getCipherFormat()
132
    {
133
        return $this->cipherFormat;
134
    }
135
}
136