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

User::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
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 "user"
28
 *
29
 * @link https://tools.ietf.org/html/rfc3986#section-3.2.1
30
 */
31
final class User 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 62
    public function __construct($value)
57
    {
58 62
        if ($value === '') {
59 2
            return;
60
        }
61
62 62
        if (!is_string($value)) {
63 9
            throw new InvalidUriComponentException('URI component "user" must be a string');
64
        }
65
66 53
        $this->value = preg_replace_callback(self::NORMALIZE_REGEX, function (array $match): string {
67
            /** @var array{0: string, 1?: string} $match */
68
69 53
            return isset($match[1]) ? rawurlencode($match[1]) : $match[0];
70 53
        }, $value);
71
    }
72
73
    /**
74
     * Creates a user component
75
     *
76
     * @param mixed $user
77
     *
78
     * @return User
79
     *
80
     * @throws InvalidUriComponentException
81
     */
82 62
    public static function create($user): User
83
    {
84 62
        if ($user instanceof User) {
85
            return $user;
86
        }
87
88 62
        return new User($user);
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @return string
95
     */
96 45
    public function getValue(): string
97
    {
98 45
        return $this->value;
99
    }
100
}
101