/
IriHelper.php
107 lines (86 loc) · 2.92 KB
/
IriHelper.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
107
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Util;
use ApiPlatform\Api\UrlGeneratorInterface;
use ApiPlatform\Exception\InvalidArgumentException;
/**
* Parses and creates IRIs.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @internal
*/
final class IriHelper
{
private function __construct()
{
}
/**
* Parses and standardizes the request IRI.
*
* @throws InvalidArgumentException
*/
public static function parseIri(string $iri, string $pageParameterName): array
{
$parts = parse_url($iri);
if (false === $parts) {
throw new InvalidArgumentException(sprintf('The request URI "%s" is malformed.', $iri));
}
$parameters = [];
if (isset($parts['query'])) {
$parameters = RequestParser::parseRequestParams($parts['query']);
// Remove existing page parameter
unset($parameters[$pageParameterName]);
}
return ['parts' => $parts, 'parameters' => $parameters];
}
/**
* Gets a collection IRI for the given parameters.
*/
public static function createIri(array $parts, array $parameters, string $pageParameterName = null, float $page = null, $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH): string
{
if (null !== $page && null !== $pageParameterName) {
$parameters[$pageParameterName] = $page;
}
$query = http_build_query($parameters, '', '&', \PHP_QUERY_RFC3986);
$parts['query'] = preg_replace('/%5B\d+%5D/', '%5B%5D', $query);
$url = '';
if ((UrlGeneratorInterface::ABS_URL === $urlGenerationStrategy || UrlGeneratorInterface::NET_PATH === $urlGenerationStrategy) && isset($parts['host'])) {
if (isset($parts['scheme'])) {
$scheme = $parts['scheme'];
} elseif (isset($parts['port']) && 443 === $parts['port']) {
$scheme = 'https';
} else {
$scheme = 'http';
}
$url .= UrlGeneratorInterface::NET_PATH === $urlGenerationStrategy ? '//' : "$scheme://";
if (isset($parts['user'])) {
$url .= $parts['user'];
if (isset($parts['pass'])) {
$url .= ':'.$parts['pass'];
}
$url .= '@';
}
$url .= $parts['host'];
if (isset($parts['port'])) {
$url .= ':'.$parts['port'];
}
}
$url .= $parts['path'];
if ('' !== $parts['query']) {
$url .= '?'.$parts['query'];
}
if (isset($parts['fragment'])) {
$url .= '#'.$parts['fragment'];
}
return $url;
}
}