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 "query" |
28
|
|
|
* |
29
|
|
|
* @link https://tools.ietf.org/html/rfc3986#section-3.4 |
30
|
|
|
*/ |
31
|
|
|
final class Query 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
|
57 |
|
public function __construct($value) |
57
|
|
|
{ |
58
|
57 |
|
if ($value === '') { |
59
|
1 |
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
57 |
|
if (!is_string($value)) { |
63
|
9 |
|
throw new InvalidUriComponentException('URI component "query" must be a string'); |
64
|
|
|
} |
65
|
|
|
|
66
|
48 |
|
$this->value = preg_replace_callback(self::NORMALIZE_REGEX, function (array $match): string { |
67
|
|
|
/** @var array{0: string, 1?: string} $match */ |
68
|
|
|
|
69
|
48 |
|
return isset($match[1]) ? rawurlencode($match[1]) : $match[0]; |
70
|
48 |
|
}, $value); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* {@inheritdoc} |
75
|
|
|
* |
76
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
48 |
|
public function getValue(): string |
79
|
|
|
{ |
80
|
48 |
|
return $this->value; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|