Passed
Pull Request — master (#31)
by Anatoly
39:30
created

Password::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 15
ccs 7
cts 8
cp 0.875
crap 4.0312
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\InvalidUriComponentException;
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 to normalize the component value
36
     *
37
     * @var string
38
     */
39
    private const NORMALIZE_REGEX = '/(?:(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-\._~\!\$&\'\(\)\*\+,;\=]+)|(.?))/u';
40
41
    /**
42
     * The component value
43
     *
44
     * @var string
45
     */
46
    private string $value = '';
47
48
    /**
49
     * Constructor of the class
50
     *
51
     * @param mixed $value
52
     *
53
     * @throws InvalidUriComponentException
54
     *         If the component isn't valid.
55
     */
56 52
    public function __construct($value)
57
    {
58 52
        if ($value === '') {
59
            return;
60
        }
61
62 52
        if (!is_string($value)) {
63 8
            throw new InvalidUriComponentException('URI component "password" must be a string');
64
        }
65
66 44
        $this->value = preg_replace_callback(self::NORMALIZE_REGEX, function (array $match): string {
67
            /** @var array{0: string, 1?: string} $match */
68
69 44
            return isset($match[1]) ? rawurlencode($match[1]) : $match[0];
70 44
        }, $value);
71
    }
72
73
    /**
74
     * Creates a password component
75
     *
76
     * @param mixed $password
77
     *
78
     * @return Password
79
     *
80
     * @throws InvalidUriComponentException
81
     */
82 52
    public static function create($password): Password
83
    {
84 52
        if ($password instanceof Password) {
85
            return $password;
86
        }
87
88 52
        return new Password($password);
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @return string
95
     */
96 44
    public function getValue(): string
97
    {
98 44
        return $this->value;
99
    }
100
}
101