Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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
namespace Symfony\Component\Routing\Generator;
13
 
14
use Psr\Log\LoggerInterface;
15
use Symfony\Component\Routing\Exception\InvalidParameterException;
16
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
17
use Symfony\Component\Routing\Exception\RouteNotFoundException;
18
use Symfony\Component\Routing\RequestContext;
19
use Symfony\Component\Routing\RouteCollection;
20
 
21
/**
22
 * UrlGenerator can generate a URL or a path for any route in the RouteCollection
23
 * based on the passed parameters.
24
 *
25
 * @author Fabien Potencier <fabien@symfony.com>
26
 * @author Tobias Schultze <http://tobion.de>
27
 */
28
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
29
{
30
    private const QUERY_FRAGMENT_DECODED = [
31
        // RFC 3986 explicitly allows those in the query/fragment to reference other URIs unencoded
32
        '%2F' => '/',
33
        '%252F' => '%2F',
34
        '%3F' => '?',
35
        // reserved chars that have no special meaning for HTTP URIs in a query or fragment
36
        // this excludes esp. "&", "=" and also "+" because PHP would treat it as a space (form-encoded)
37
        '%40' => '@',
38
        '%3A' => ':',
39
        '%21' => '!',
40
        '%3B' => ';',
41
        '%2C' => ',',
42
        '%2A' => '*',
43
    ];
44
 
45
    protected $routes;
46
    protected $context;
47
 
48
    /**
49
     * @var bool|null
50
     */
51
    protected $strictRequirements = true;
52
 
53
    protected $logger;
54
 
55
    private ?string $defaultLocale;
56
 
57
    /**
58
     * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
59
     *
60
     * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
61
     * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
62
     * "?" and "#" (would be interpreted wrongly as query and fragment identifier),
63
     * "'" and """ (are used as delimiters in HTML).
64
     */
65
    protected $decodedChars = [
66
        // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
67
        // some webservers don't allow the slash in encoded form in the path for security reasons anyway
68
        // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
69
        '%2F' => '/',
70
        '%252F' => '%2F',
71
        // the following chars are general delimiters in the URI specification but have only special meaning in the authority component
72
        // so they can safely be used in the path in unencoded form
73
        '%40' => '@',
74
        '%3A' => ':',
75
        // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
76
        // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
77
        '%3B' => ';',
78
        '%2C' => ',',
79
        '%3D' => '=',
80
        '%2B' => '+',
81
        '%21' => '!',
82
        '%2A' => '*',
83
        '%7C' => '|',
84
    ];
85
 
86
    public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null, string $defaultLocale = null)
87
    {
88
        $this->routes = $routes;
89
        $this->context = $context;
90
        $this->logger = $logger;
91
        $this->defaultLocale = $defaultLocale;
92
    }
93
 
94
    public function setContext(RequestContext $context)
95
    {
96
        $this->context = $context;
97
    }
98
 
99
    public function getContext(): RequestContext
100
    {
101
        return $this->context;
102
    }
103
 
104
    public function setStrictRequirements(?bool $enabled)
105
    {
106
        $this->strictRequirements = $enabled;
107
    }
108
 
109
    public function isStrictRequirements(): ?bool
110
    {
111
        return $this->strictRequirements;
112
    }
113
 
114
    public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string
115
    {
116
        $route = null;
117
        $locale = $parameters['_locale'] ?? $this->context->getParameter('_locale') ?: $this->defaultLocale;
118
 
119
        if (null !== $locale) {
120
            do {
121
                if (null !== ($route = $this->routes->get($name.'.'.$locale)) && $route->getDefault('_canonical_route') === $name) {
122
                    break;
123
                }
124
            } while (false !== $locale = strstr($locale, '_', true));
125
        }
126
 
127
        if (null === $route ??= $this->routes->get($name)) {
128
            throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
129
        }
130
 
131
        // the Route has a cache of its own and is not recompiled as long as it does not get modified
132
        $compiledRoute = $route->compile();
133
 
134
        $defaults = $route->getDefaults();
135
        $variables = $compiledRoute->getVariables();
136
 
137
        if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
138
            if (!\in_array('_locale', $variables, true)) {
139
                unset($parameters['_locale']);
140
            } elseif (!isset($parameters['_locale'])) {
141
                $parameters['_locale'] = $defaults['_locale'];
142
            }
143
        }
144
 
145
        return $this->doGenerate($variables, $defaults, $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
146
    }
147
 
148
    /**
149
     * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
150
     * @throws InvalidParameterException           When a parameter value for a placeholder is not correct because
151
     *                                             it does not match the requirement
152
     */
153
    protected function doGenerate(array $variables, array $defaults, array $requirements, array $tokens, array $parameters, string $name, int $referenceType, array $hostTokens, array $requiredSchemes = []): string
154
    {
155
        $variables = array_flip($variables);
156
        $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
157
 
158
        // all params must be given
159
        if ($diff = array_diff_key($variables, $mergedParams)) {
160
            throw new MissingMandatoryParametersException($name, array_keys($diff));
161
        }
162
 
163
        $url = '';
164
        $optional = true;
165
        $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.';
166
        foreach ($tokens as $token) {
167
            if ('variable' === $token[0]) {
168
                $varName = $token[3];
169
                // variable is not important by default
170
                $important = $token[5] ?? false;
171
 
172
                if (!$optional || $important || !\array_key_exists($varName, $defaults) || (null !== $mergedParams[$varName] && (string) $mergedParams[$varName] !== (string) $defaults[$varName])) {
173
                    // check requirement (while ignoring look-around patterns)
174
                    if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\(\?(?:=|<=|!|<!)((?:[^()\\\\]+|\\\\.|\((?1)\))*)\)/', '', $token[2]).'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]] ?? '')) {
175
                        if ($this->strictRequirements) {
176
                            throw new InvalidParameterException(strtr($message, ['{parameter}' => $varName, '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$varName]]));
177
                        }
178
 
179
                        $this->logger?->error($message, ['parameter' => $varName, 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$varName]]);
180
 
181
                        return '';
182
                    }
183
 
184
                    $url = $token[1].$mergedParams[$varName].$url;
185
                    $optional = false;
186
                }
187
            } else {
188
                // static text
189
                $url = $token[1].$url;
190
                $optional = false;
191
            }
192
        }
193
 
194
        if ('' === $url) {
195
            $url = '/';
196
        }
197
 
198
        // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
199
        $url = strtr(rawurlencode($url), $this->decodedChars);
200
 
201
        // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
202
        // so we need to encode them as they are not used for this purpose here
203
        // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
204
        $url = strtr($url, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);
205
        if (str_ends_with($url, '/..')) {
206
            $url = substr($url, 0, -2).'%2E%2E';
207
        } elseif (str_ends_with($url, '/.')) {
208
            $url = substr($url, 0, -1).'%2E';
209
        }
210
 
211
        $schemeAuthority = '';
212
        $host = $this->context->getHost();
213
        $scheme = $this->context->getScheme();
214
 
215
        if ($requiredSchemes) {
216
            if (!\in_array($scheme, $requiredSchemes, true)) {
217
                $referenceType = self::ABSOLUTE_URL;
218
                $scheme = current($requiredSchemes);
219
            }
220
        }
221
 
222
        if ($hostTokens) {
223
            $routeHost = '';
224
            foreach ($hostTokens as $token) {
225
                if ('variable' === $token[0]) {
226
                    // check requirement (while ignoring look-around patterns)
227
                    if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\(\?(?:=|<=|!|<!)((?:[^()\\\\]+|\\\\.|\((?1)\))*)\)/', '', $token[2]).'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
228
                        if ($this->strictRequirements) {
229
                            throw new InvalidParameterException(strtr($message, ['{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]]));
230
                        }
231
 
232
                        $this->logger?->error($message, ['parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]]);
233
 
234
                        return '';
235
                    }
236
 
237
                    $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
238
                } else {
239
                    $routeHost = $token[1].$routeHost;
240
                }
241
            }
242
 
243
            if ($routeHost !== $host) {
244
                $host = $routeHost;
245
                if (self::ABSOLUTE_URL !== $referenceType) {
246
                    $referenceType = self::NETWORK_PATH;
247
                }
248
            }
249
        }
250
 
251
        if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
252
            if ('' !== $host || ('' !== $scheme && 'http' !== $scheme && 'https' !== $scheme)) {
253
                $port = '';
254
                if ('http' === $scheme && 80 !== $this->context->getHttpPort()) {
255
                    $port = ':'.$this->context->getHttpPort();
256
                } elseif ('https' === $scheme && 443 !== $this->context->getHttpsPort()) {
257
                    $port = ':'.$this->context->getHttpsPort();
258
                }
259
 
260
                $schemeAuthority = self::NETWORK_PATH === $referenceType || '' === $scheme ? '//' : "$scheme://";
261
                $schemeAuthority .= $host.$port;
262
            }
263
        }
264
 
265
        if (self::RELATIVE_PATH === $referenceType) {
266
            $url = self::getRelativePath($this->context->getPathInfo(), $url);
267
        } else {
268
            $url = $schemeAuthority.$this->context->getBaseUrl().$url;
269
        }
270
 
271
        // add a query string if needed
272
        $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
273
            return $a == $b ? 0 : 1;
274
        });
275
 
276
        array_walk_recursive($extra, $caster = static function (&$v) use (&$caster) {
277
            if (\is_object($v)) {
278
                if ($vars = get_object_vars($v)) {
279
                    array_walk_recursive($vars, $caster);
280
                    $v = $vars;
281
                } elseif (method_exists($v, '__toString')) {
282
                    $v = (string) $v;
283
                }
284
            }
285
        });
286
 
287
        // extract fragment
288
        $fragment = $defaults['_fragment'] ?? '';
289
 
290
        if (isset($extra['_fragment'])) {
291
            $fragment = $extra['_fragment'];
292
            unset($extra['_fragment']);
293
        }
294
 
295
        if ($extra && $query = http_build_query($extra, '', '&', \PHP_QUERY_RFC3986)) {
296
            $url .= '?'.strtr($query, self::QUERY_FRAGMENT_DECODED);
297
        }
298
 
299
        if ('' !== $fragment) {
300
            $url .= '#'.strtr(rawurlencode($fragment), self::QUERY_FRAGMENT_DECODED);
301
        }
302
 
303
        return $url;
304
    }
305
 
306
    /**
307
     * Returns the target path as relative reference from the base path.
308
     *
309
     * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
310
     * Both paths must be absolute and not contain relative parts.
311
     * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
312
     * Furthermore, they can be used to reduce the link size in documents.
313
     *
314
     * Example target paths, given a base path of "/a/b/c/d":
315
     * - "/a/b/c/d"     -> ""
316
     * - "/a/b/c/"      -> "./"
317
     * - "/a/b/"        -> "../"
318
     * - "/a/b/c/other" -> "other"
319
     * - "/a/x/y"       -> "../../x/y"
320
     *
321
     * @param string $basePath   The base path
322
     * @param string $targetPath The target path
323
     */
324
    public static function getRelativePath(string $basePath, string $targetPath): string
325
    {
326
        if ($basePath === $targetPath) {
327
            return '';
328
        }
329
 
330
        $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
331
        $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
332
        array_pop($sourceDirs);
333
        $targetFile = array_pop($targetDirs);
334
 
335
        foreach ($sourceDirs as $i => $dir) {
336
            if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
337
                unset($sourceDirs[$i], $targetDirs[$i]);
338
            } else {
339
                break;
340
            }
341
        }
342
 
343
        $targetDirs[] = $targetFile;
344
        $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
345
 
346
        // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
347
        // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
348
        // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
349
        // (see http://tools.ietf.org/html/rfc3986#section-4.2).
350
        return '' === $path || '/' === $path[0]
351
            || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
352
            ? "./$path" : $path;
353
    }
354
}