Test Failed
Pull Request — master (#31)
by Anatoly
33:35 queued 29:37
created

Password::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-message
10
 */
11
12
namespace Sunrise\Http\Message\Uri\Component;
13
14
/**
15
 * Import classes
16
 */
17
use Sunrise\Http\Message\Exception\InvalidArgumentException;
18
19
/**
20
 * Import functions
21
 */
22
use function is_string;
23
use function preg_replace_callback;
24
use function rawurlencode;
25
26
/**
27
 * URI component "password"
28
 *
29
 * @link https://tools.ietf.org/html/rfc3986#section-3.2.1
30
 */
31
final class Password implements ComponentInterface
32
{
33
34
    /**
35
     * Regular expression used for the component normalization
36
     *
37
     * @var string
38
     */
39
    // phpcs:ignore Generic.Files.LineLength
40
    private const NORMALIZATION_REGEX = '/(?:%[0-9A-Fa-f]{2}|[\x21\x24\x26-\x2e\x30-\x39\x3b\x3d\x41-\x5a\x5f\x61-\x7a\x7e]+)|(.?)/u';
41
42
    /**
43
     * The component value
44
     *
45
     * @var string
46
     */
47
    private string $value = '';
48
49
    /**
50
     * Constructor of the class
51
     *
52
     * @param mixed $value
53
     *
54
     * @throws InvalidArgumentException
55
     *         If the component isn't valid.
56 51
     */
57
    public function __construct($value)
58 51
    {
59
        if ($value === '') {
60
            return;
61
        }
62 51
63 8
        if (!is_string($value)) {
64
            throw new InvalidArgumentException('URI component "password" must be a string');
65
        }
66 43
67
        $this->value = preg_replace_callback(self::NORMALIZATION_REGEX, static function (array $match): string {
68
            /** @var array{0: string, 1?: string} $match */
69 43
70 43
            return isset($match[1]) ? rawurlencode($match[1]) : $match[0];
71
        }, $value);
72
    }
73
74
    /**
75
     * Creates a password component
76
     *
77
     * @param mixed $password
78 43
     *
79
     * @return Password
80 43
     *
81
     * @throws InvalidArgumentException
82
     */
83
    public static function create($password): Password
84
    {
85
        if ($password instanceof Password) {
86
            return $password;
87
        }
88
89
        return new Password($password);
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     *
95
     * @return string
96
     */
97
    public function getValue(): string
98
    {
99
        return $this->value;
100
    }
101
}
102