Passed
Pull Request — master (#27)
by Anatoly
04:06
created

Host   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 53
ccs 11
cts 11
cp 1
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 4
A getValue() 0 3 1
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
use function strtolower;
26
27
/**
28
 * URI component "host"
29
 *
30
 * @link https://tools.ietf.org/html/rfc3986#section-3.2.2
31
 */
32
final class Host implements ComponentInterface
33
{
34
35
    /**
36
     * Regular expression to normalize the component value
37
     *
38
     * @var string
39
     */
40
    private const NORMALIZE_REGEX = '/(?:(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-\._~\!\$&\'\(\)\*\+,;\=]+)|(.?))/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 InvalidUriComponentException
55
     *         If the component isn't valid.
56
     */
57 128
    public function __construct($value)
58
    {
59 128
        if ($value === '') {
60 2
            return;
61
        }
62
63 128
        if (!is_string($value)) {
64 9
            throw new InvalidUriComponentException('URI component "host" must be a string');
65
        }
66
67 119
        $this->value = preg_replace_callback(self::NORMALIZE_REGEX, function (array $match): string {
68
            /** @var array{0: string, 1?: string} $match */
69
70 119
            return isset($match[1]) ? rawurlencode($match[1]) : $match[0];
71 119
        }, $value);
72
73
        // the component is case-insensitive...
74 119
        $this->value = strtolower($this->value);
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     *
80
     * @return string
81
     */
82 119
    public function getValue(): string
83
    {
84 119
        return $this->value;
85
    }
86
}
87