|
2 | 2 |
|
3 | 3 | namespace wcf\util; |
4 | 4 |
|
| 5 | +use GuzzleHttp\Psr7\Uri; |
| 6 | +use Psr\Http\Message\UriInterface; |
| 7 | + |
5 | 8 | /** |
6 | 9 | * Generic wrapper around `parse_url()`. |
7 | 10 | * |
@@ -216,4 +219,75 @@ public static function getHostnameMatcher(array $hostnames): callable |
216 | 219 | return false; |
217 | 220 | }; |
218 | 221 | } |
| 222 | + |
| 223 | + /** |
| 224 | + * Appends a query string and an optional fragment to an existing URI. |
| 225 | + * |
| 226 | + * @since 6.3 |
| 227 | + */ |
| 228 | + public static function withQueryString(string|Uri $uri, string $queryString): UriInterface |
| 229 | + { |
| 230 | + if (\is_string($uri)) { |
| 231 | + $uri = new Uri($uri); |
| 232 | + } |
| 233 | + |
| 234 | + if ($queryString === '') { |
| 235 | + return $uri; |
| 236 | + } |
| 237 | + |
| 238 | + $anchorPosition = \mb_strpos($queryString, '#'); |
| 239 | + if ($anchorPosition !== false) { |
| 240 | + $anchor = \mb_substr($queryString, $anchorPosition + 1); |
| 241 | + $queryString = \mb_substr($queryString, 0, $anchorPosition); |
| 242 | + |
| 243 | + $uri = $uri->withFragment($anchor); |
| 244 | + } |
| 245 | + |
| 246 | + if ($queryString === '') { |
| 247 | + return $uri; |
| 248 | + } |
| 249 | + |
| 250 | + \parse_str($queryString, $parts); |
| 251 | + |
| 252 | + $flattenedParts = []; |
| 253 | + foreach ($parts as $key => $value) { |
| 254 | + self::flattenQueryKey($key, $value, $flattenedParts); |
| 255 | + } |
| 256 | + |
| 257 | + return $uri->withQueryValues($uri, $flattenedParts); |
| 258 | + } |
| 259 | + |
| 260 | + /** |
| 261 | + * PHP’s `parse_str()` splits a query string into an array but nested keys |
| 262 | + * using the square bracket notation are parsed into nested arrays. This |
| 263 | + * conflicts with `Uri::withQueryValues()` that expects a one-dimensional |
| 264 | + * array with keys using the bracket notation. |
| 265 | + * |
| 266 | + * This method recursively processes the value with each child key added to |
| 267 | + * the `$key` value using the bracket notation. |
| 268 | + * |
| 269 | + * @param string|array<string, string> $value |
| 270 | + * @param array<string, string> &$flattenedParts |
| 271 | + * @since 6.3 |
| 272 | + */ |
| 273 | + private static function flattenQueryKey(string $key, string|array $value, array &$flattenedParts): void |
| 274 | + { |
| 275 | + if (\is_string($value)) { |
| 276 | + $flattenedParts[$key] = $value; |
| 277 | + |
| 278 | + return; |
| 279 | + } |
| 280 | + |
| 281 | + foreach ($value as $subKey => $subValue) { |
| 282 | + self::flattenQueryKey( |
| 283 | + \sprintf( |
| 284 | + '%s[%s]', |
| 285 | + $key, |
| 286 | + $subKey |
| 287 | + ), |
| 288 | + $subValue, |
| 289 | + $flattenedParts, |
| 290 | + ); |
| 291 | + } |
| 292 | + } |
219 | 293 | } |
0 commit comments