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