-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryStringUtil.php
106 lines (92 loc) · 2.98 KB
/
QueryStringUtil.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Oro\Component\PhpUtils;
/**
* Provides a set of reusable static methods to build URL-encoded query string.
*/
final class QueryStringUtil
{
/**
* Builds URL-encoded query string.
*
* @param array $params [key => string value, ...]
*
* @return string
*/
public static function buildQueryString(array $params): string
{
// assert that all values are string
foreach ($params as $name => $value) {
if (!is_string($value)) {
throw new \UnexpectedValueException(sprintf(
'Expected string value for the parameter "%s", given "%s".',
$name,
is_object($value) ? get_class($value) : gettype($value)
));
}
}
return self::httpBuildQuery($params);
}
/**
* Adds URL-encoded query string to URL.
*/
public static function addQueryString(string $url, string $queryString): string
{
if ($queryString) {
$url .= (false === strrpos($url, '?') ? '?' : '&') . $queryString;
}
return $url;
}
/**
* Adds a parameter to URL-encoded query string.
* If the query string already contains a parameter with the given name
* its value will be overridden with the new value.
*/
public static function addParameter(string $queryString, string $name, string $value): string
{
parse_str($queryString, $params);
parse_str(self::httpBuildQuery([urldecode($name) => $value]), $addingParam);
$params = array_replace_recursive($params, $addingParam);
return self::httpBuildQuery($params);
}
/**
* Removes a parameter from URL-encoded query string.
*/
public static function removeParameter(string $queryString, string $name): string
{
parse_str($queryString, $params);
parse_str(self::httpBuildQuery([urldecode($name) => '']), $removingParam);
$path = [];
$val = reset($removingParam);
$path[] = key($removingParam);
while (is_array($val)) {
$path[] = key($val);
$val = reset($val);
}
return self::httpBuildQuery(self::unsetParameterByPath($params, $path));
}
private static function httpBuildQuery(array $params): string
{
return http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
/**
* @param array $params
* @param array $path
*
* @return array
*/
private static function unsetParameterByPath(array $params, array $path)
{
$key = array_shift($path);
if (empty($path)) {
unset($params[$key]);
} elseif (array_key_exists($key, $params) && is_array($params[$key])) {
$value = self::unsetParameterByPath($params[$key], $path);
if (empty($value)) {
unset($params[$key]);
} else {
$params[$key] = $value;
}
}
return $params;
}
}