Subversion Repositories php-qbpwcf

Rev

Details | Last modification | View Log | RSS feed

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