User::getValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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
use Sunrise\Http\Message\Exception\InvalidArgumentException;
15
16
use function is_string;
17
use function preg_replace_callback;
18
use function rawurlencode;
19
20
/**
21
 * @link https://tools.ietf.org/html/rfc3986#section-3.2.1
22
 */
23
final class User implements ComponentInterface
24
{
25
    // phpcs:ignore Generic.Files.LineLength
26
    private const NORMALIZATION_REGEX = '/(?:%[0-9A-Fa-f]{2}|[\x21\x24\x26-\x2e\x30-\x39\x3b\x3d\x41-\x5a\x5f\x61-\x7a\x7e]+)|(.?)/u';
27
28
    private string $value = '';
29
30
    /**
31
     * @param mixed $value
32
     *
33
     * @throws InvalidArgumentException
34
     */
35 62
    public function __construct($value)
36
    {
37 62
        if ($value === '') {
38 2
            return;
39
        }
40
41 62
        if (!is_string($value)) {
42 9
            throw new InvalidArgumentException('URI component "user" must be a string');
43
        }
44
45 53
        $this->value = (string) preg_replace_callback(
46 53
            self::NORMALIZATION_REGEX,
47 53
            static fn(array $matches): string => (
48
                /** @var array{0: string, 1?: string} $matches */
49 53
                isset($matches[1]) ? rawurlencode($matches[1]) : $matches[0]
50 53
            ),
51 53
            $value,
52 53
        );
53
    }
54
55
    /**
56
     * @param mixed $user
57
     *
58
     * @throws InvalidArgumentException
59
     */
60 62
    public static function create($user): User
61
    {
62 62
        if ($user instanceof User) {
63
            return $user;
64
        }
65
66 62
        return new User($user);
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     *
72
     * @return string
73
     */
74 45
    public function getValue(): string
75
    {
76 45
        return $this->value;
77
    }
78
}
79