vendor/guzzlehttp/psr7/src/UriResolver.php
237 lines · 9613 bytes
1<?php
2
3declare(strict_types=1);
4
5namespace GuzzleHttp\Psr7;
6
7use Psr\Http\Message\UriInterface;
8
9/**
10 * Resolves a URI reference in the context of a base URI and the opposite way.
11 *
12 * @author Tobias Schultze
13 *
14 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5
15 */
16final class UriResolver
17{
18 /**
19 * Removes dot segments from a path and returns the new path.
20 *
21 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
22 */
23 public static function removeDotSegments(string $path): string
24 {
25 if ($path === '' || $path === '/') {
26 return $path;
27 }
28
29 $results = [];
30 $segments = explode('/', $path);
31 foreach ($segments as $segment) {
32 if ($segment === '..') {
33 array_pop($results);
34 } elseif ($segment !== '.') {
35 $results[] = $segment;
36 }
37 }
38
39 $newPath = implode('/', $results);
40
41 if ($path[0] === '/' && (!isset($newPath[0]) || $newPath[0] !== '/')) {
42 // Re-add the leading slash if necessary for cases like "/.."
43 $newPath = '/'.$newPath;
44 } elseif ($newPath !== '' && ($segment === '.' || $segment === '..')) {
45 // Add the trailing slash if necessary
46 // If newPath is not empty, then $segment must be set and is the last segment from the foreach
47 $newPath .= '/';
48 }
49
50 return $newPath;
51 }
52
53 /**
54 * Returns the path, prefixed with "./" when it would otherwise begin a relative-path reference with a segment
55 * containing a colon.
56 *
57 * Such a segment would be mistaken for a scheme name (RFC 3986 Section 4.2), so a URI without a scheme and
58 * authority cannot hold the path, but reference resolution and percent-encoding normalization can produce one.
59 * The "./" prefix the RFC prescribes resolves back to the same path.
60 *
61 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
62 *
63 * @internal
64 */
65 public static function guardedPath(UriInterface $uri, string $path): string
66 {
67 if ($uri->getScheme() !== '' || $uri->getAuthority() !== '' || strpos(explode('/', $path, 2)[0], ':') === false) {
68 return $path;
69 }
70
71 return './'.$path;
72 }
73
74 /**
75 * Converts the relative URI into a new URI that is resolved against the base URI.
76 *
77 * When the resolved path is a relative-path reference whose first segment contains a colon,
78 * which would be mistaken for a scheme name (RFC 3986 Section 4.2), it is prefixed with "./",
79 * e.g. "./a:b".
80 *
81 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2
82 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
83 */
84 public static function resolve(UriInterface $base, UriInterface $rel): UriInterface
85 {
86 if ((string) $rel === '') {
87 // we can simply return the same base URI instance for this same-document reference
88 return $base;
89 }
90
91 if ($rel->getScheme() != '') {
92 return $rel->withPath(self::removeDotSegments($rel->getPath()));
93 }
94
95 if ($rel->getAuthority() != '') {
96 return $rel
97 ->withScheme($base->getScheme())
98 ->withPath(self::removeDotSegments($rel->getPath()));
99 }
100
101 if ($rel->getPath() === '') {
102 $targetPath = $base->getPath();
103 $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery();
104 } else {
105 if ($rel->getPath()[0] === '/') {
106 $targetPath = $rel->getPath();
107 } else {
108 if ($base->getAuthority() != '' && $base->getPath() === '') {
109 $targetPath = '/'.$rel->getPath();
110 } else {
111 $lastSlashPos = strrpos($base->getPath(), '/');
112 if ($lastSlashPos === false) {
113 $targetPath = $rel->getPath();
114 } else {
115 $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1).$rel->getPath();
116 }
117 }
118 }
119 $targetPath = self::removeDotSegments($targetPath);
120 $targetQuery = $rel->getQuery();
121 }
122
123 if ($targetPath !== $base->getPath()) {
124 $targetPath = self::guardedPath($base, $targetPath);
125 }
126
127 return $base
128 ->withPath($targetPath)
129 ->withQuery($targetQuery)
130 ->withFragment($rel->getFragment());
131 }
132
133 /**
134 * Returns the target URI as a relative reference from the base URI.
135 *
136 * This method is the counterpart to resolve():
137 *
138 * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
139 *
140 * One use-case is to use the current request URI as base URI and then generate relative links in your documents
141 * to reduce the document size or offer self-contained downloadable document archives.
142 *
143 * $base = new Uri('http://example.com/a/b/');
144 * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
145 * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
146 * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
147 * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
148 *
149 * This method also accepts a target that is already relative and will try to relativize it further. Only a
150 * relative-path reference will be returned as-is.
151 *
152 * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well
153 */
154 public static function relativize(UriInterface $base, UriInterface $target): UriInterface
155 {
156 if ($target->getScheme() !== ''
157 && ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
158 ) {
159 return $target;
160 }
161
162 if (Uri::isRelativePathReference($target)) {
163 // As the target is already highly relative we return it as-is. It would be possible to resolve
164 // the target with `$target = self::resolve($base, $target);` and then try make it more relative
165 // by removing a duplicate query. But let's not do that automatically.
166 return $target;
167 }
168
169 if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) {
170 return $target->withScheme('');
171 }
172
173 // We must remove the path before removing the authority because if the path starts with two slashes, the URI
174 // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also
175 // invalid.
176 $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost('');
177
178 if ($base->getPath() !== $target->getPath()) {
179 return $emptyPathUri->withPath(self::getRelativePath($base, $target));
180 }
181
182 if ($base->getQuery() === $target->getQuery()) {
183 // Only the target fragment is left. And it must be returned even if base and target fragment are the same.
184 return $emptyPathUri->withQuery('');
185 }
186
187 // If the base URI has a query but the target has none, we cannot return an empty path reference as it would
188 // inherit the base query component when resolving.
189 if ($target->getQuery() === '') {
190 $segments = explode('/', $target->getPath());
191 /** @var string $lastSegment */
192 $lastSegment = end($segments);
193
194 return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment);
195 }
196
197 return $emptyPathUri;
198 }
199
200 private static function getRelativePath(UriInterface $base, UriInterface $target): string
201 {
202 $sourceSegments = explode('/', $base->getPath());
203 $targetSegments = explode('/', $target->getPath());
204 array_pop($sourceSegments);
205 $targetLastSegment = array_pop($targetSegments);
206 foreach ($sourceSegments as $i => $segment) {
207 if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) {
208 unset($sourceSegments[$i], $targetSegments[$i]);
209 } else {
210 break;
211 }
212 }
213 $targetSegments[] = $targetLastSegment;
214 $relativePath = str_repeat('../', count($sourceSegments)).implode('/', $targetSegments);
215
216 // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./".
217 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
218 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name.
219 if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) {
220 $relativePath = "./$relativePath";
221 } elseif ('/' === $relativePath[0]) {
222 if ($base->getAuthority() != '' && $base->getPath() === '') {
223 // In this case an extra slash is added by resolve() automatically. So we must not add one here.
224 $relativePath = ".$relativePath";
225 } else {
226 $relativePath = "./$relativePath";
227 }
228 }
229
230 return $relativePath;
231 }
232
233 private function __construct()
234 {
235 // cannot be instantiated
236 }
237}