1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the API Platform project. |
5
|
|
|
* |
6
|
|
|
* (c) Kévin Dunglas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace ApiPlatform\Core\Util; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Exception\InvalidArgumentException; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Parses and creates IRIs. |
20
|
|
|
* |
21
|
|
|
* @author Kévin Dunglas <[email protected]> |
22
|
|
|
* |
23
|
|
|
* @internal |
24
|
|
|
*/ |
25
|
|
|
final class IriHelper |
26
|
|
|
{ |
27
|
|
|
private function __construct() |
28
|
|
|
{ |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Parses and standardizes the request IRI. |
33
|
|
|
* |
34
|
|
|
* @param string $iri |
35
|
|
|
* @param string $pageParameterName |
36
|
|
|
* |
37
|
|
|
* @throws InvalidArgumentException |
38
|
|
|
* |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
|
|
public static function parseIri(string $iri, string $pageParameterName): array |
42
|
|
|
{ |
43
|
|
|
$parts = parse_url($iri); |
44
|
|
|
if (false === $parts) { |
45
|
|
|
throw new InvalidArgumentException(sprintf('The request URI "%s" is malformed.', $iri)); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$parameters = []; |
49
|
|
|
if (isset($parts['query'])) { |
50
|
|
|
$parameters = RequestParser::parseRequestParams($parts['query']); |
51
|
|
|
|
52
|
|
|
// Remove existing page parameter |
53
|
|
|
unset($parameters[$pageParameterName]); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return ['parts' => $parts, 'parameters' => $parameters]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Gets a collection IRI for the given parameters. |
61
|
|
|
* |
62
|
|
|
* @param array $parts |
63
|
|
|
* @param array $parameters |
64
|
|
|
* @param string $pageParameterName |
65
|
|
|
* @param float $page |
66
|
|
|
* |
67
|
|
|
* @return string |
68
|
|
|
*/ |
69
|
|
|
public static function createIri(array $parts, array $parameters, string $pageParameterName, float $page = null): string |
70
|
|
|
{ |
71
|
|
|
if (null !== $page) { |
72
|
|
|
$parameters[$pageParameterName] = $page; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$query = http_build_query($parameters, '', '&', PHP_QUERY_RFC3986); |
76
|
|
|
$parts['query'] = preg_replace('/%5B[0-9]+%5D/', '%5B%5D', $query); |
77
|
|
|
|
78
|
|
|
$url = $parts['path']; |
79
|
|
|
|
80
|
|
|
if ('' !== $parts['query']) { |
81
|
|
|
$url .= '?'.$parts['query']; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $url; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|