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\Matcher;
13
 
14
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
15
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
18
use Symfony\Component\Routing\Exception\NoConfigurationException;
19
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
20
use Symfony\Component\Routing\RequestContext;
21
use Symfony\Component\Routing\Route;
22
use Symfony\Component\Routing\RouteCollection;
23
 
24
/**
25
 * UrlMatcher matches URL based on a set of routes.
26
 *
27
 * @author Fabien Potencier <fabien@symfony.com>
28
 */
29
class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
30
{
31
    public const REQUIREMENT_MATCH = 0;
32
    public const REQUIREMENT_MISMATCH = 1;
33
    public const ROUTE_MATCH = 2;
34
 
35
    /** @var RequestContext */
36
    protected $context;
37
 
38
    /**
39
     * Collects HTTP methods that would be allowed for the request.
40
     */
41
    protected $allow = [];
42
 
43
    /**
44
     * Collects URI schemes that would be allowed for the request.
45
     *
46
     * @internal
47
     */
48
    protected array $allowSchemes = [];
49
 
50
    protected $routes;
51
    protected $request;
52
    protected $expressionLanguage;
53
 
54
    /**
55
     * @var ExpressionFunctionProviderInterface[]
56
     */
57
    protected $expressionLanguageProviders = [];
58
 
59
    public function __construct(RouteCollection $routes, RequestContext $context)
60
    {
61
        $this->routes = $routes;
62
        $this->context = $context;
63
    }
64
 
65
    public function setContext(RequestContext $context)
66
    {
67
        $this->context = $context;
68
    }
69
 
70
    public function getContext(): RequestContext
71
    {
72
        return $this->context;
73
    }
74
 
75
    public function match(string $pathinfo): array
76
    {
77
        $this->allow = $this->allowSchemes = [];
78
 
79
        if ($ret = $this->matchCollection(rawurldecode($pathinfo) ?: '/', $this->routes)) {
80
            return $ret;
81
        }
82
 
83
        if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) {
84
            throw new NoConfigurationException();
85
        }
86
 
87
        throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
88
    }
89
 
90
    public function matchRequest(Request $request): array
91
    {
92
        $this->request = $request;
93
 
94
        $ret = $this->match($request->getPathInfo());
95
 
96
        $this->request = null;
97
 
98
        return $ret;
99
    }
100
 
101
    public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
102
    {
103
        $this->expressionLanguageProviders[] = $provider;
104
    }
105
 
106
    /**
107
     * Tries to match a URL with a set of routes.
108
     *
109
     * @param string $pathinfo The path info to be parsed
110
     *
111
     * @throws NoConfigurationException  If no routing configuration could be found
112
     * @throws ResourceNotFoundException If the resource could not be found
113
     * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
114
     */
115
    protected function matchCollection(string $pathinfo, RouteCollection $routes): array
116
    {
117
        // HEAD and GET are equivalent as per RFC
118
        if ('HEAD' === $method = $this->context->getMethod()) {
119
            $method = 'GET';
120
        }
121
        $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
122
        $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
123
 
124
        foreach ($routes as $name => $route) {
125
            $compiledRoute = $route->compile();
126
            $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
127
            $requiredMethods = $route->getMethods();
128
 
129
            // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
130
            if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
131
                continue;
132
            }
133
            $regex = $compiledRoute->getRegex();
134
 
135
            $pos = strrpos($regex, '$');
136
            $hasTrailingSlash = '/' === $regex[$pos - 1];
137
            $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
138
 
139
            if (!preg_match($regex, $pathinfo, $matches)) {
140
                continue;
141
            }
142
 
143
            $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{[\w\x80-\xFF]+\}/?$#', $route->getPath());
144
 
145
            if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
146
                if ($hasTrailingSlash) {
147
                    $matches = $m;
148
                } else {
149
                    $hasTrailingVar = false;
150
                }
151
            }
152
 
153
            $hostMatches = [];
154
            if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
155
                continue;
156
            }
157
 
158
            $attributes = $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
159
 
160
            $status = $this->handleRouteRequirements($pathinfo, $name, $route, $attributes);
161
 
162
            if (self::REQUIREMENT_MISMATCH === $status[0]) {
163
                continue;
164
            }
165
 
166
            if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
167
                if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
168
                    return $this->allow = $this->allowSchemes = [];
169
                }
170
                continue;
171
            }
172
 
173
            if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
174
                $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
175
                continue;
176
            }
177
 
178
            if ($requiredMethods && !\in_array($method, $requiredMethods)) {
179
                $this->allow = array_merge($this->allow, $requiredMethods);
180
                continue;
181
            }
182
 
183
            return array_replace($attributes, $status[1] ?? []);
184
        }
185
 
186
        return [];
187
    }
188
 
189
    /**
190
     * Returns an array of values to use as request attributes.
191
     *
192
     * As this method requires the Route object, it is not available
193
     * in matchers that do not have access to the matched Route instance
194
     * (like the PHP and Apache matcher dumpers).
195
     */
196
    protected function getAttributes(Route $route, string $name, array $attributes): array
197
    {
198
        $defaults = $route->getDefaults();
199
        if (isset($defaults['_canonical_route'])) {
200
            $name = $defaults['_canonical_route'];
201
            unset($defaults['_canonical_route']);
202
        }
203
        $attributes['_route'] = $name;
204
 
205
        return $this->mergeDefaults($attributes, $defaults);
206
    }
207
 
208
    /**
209
     * Handles specific route requirements.
210
     *
211
     * @return array The first element represents the status, the second contains additional information
212
     */
213
    protected function handleRouteRequirements(string $pathinfo, string $name, Route $route/* , array $routeParameters */): array
214
    {
215
        if (\func_num_args() < 4) {
216
            trigger_deprecation('symfony/routing', '6.1', 'The "%s()" method will have a new "array $routeParameters" argument in version 7.0, not defining it is deprecated.', __METHOD__);
217
            $routeParameters = [];
218
        } else {
219
            $routeParameters = func_get_arg(3);
220
 
221
            if (!\is_array($routeParameters)) {
222
                throw new \TypeError(sprintf('"%s": Argument $routeParameters is expected to be an array, got "%s".', __METHOD__, get_debug_type($routeParameters)));
223
            }
224
        }
225
 
226
        // expression condition
227
        if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), [
228
            'context' => $this->context,
229
            'request' => $this->request ?: $this->createRequest($pathinfo),
230
            'params' => $routeParameters,
231
        ])) {
232
            return [self::REQUIREMENT_MISMATCH, null];
233
        }
234
 
235
        return [self::REQUIREMENT_MATCH, null];
236
    }
237
 
238
    /**
239
     * Get merged default parameters.
240
     */
241
    protected function mergeDefaults(array $params, array $defaults): array
242
    {
243
        foreach ($params as $key => $value) {
244
            if (!\is_int($key) && null !== $value) {
245
                $defaults[$key] = $value;
246
            }
247
        }
248
 
249
        return $defaults;
250
    }
251
 
252
    protected function getExpressionLanguage()
253
    {
254
        if (null === $this->expressionLanguage) {
255
            if (!class_exists(ExpressionLanguage::class)) {
256
                throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
257
            }
258
            $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
259
        }
260
 
261
        return $this->expressionLanguage;
262
    }
263
 
264
    /**
265
     * @internal
266
     */
267
    protected function createRequest(string $pathinfo): ?Request
268
    {
269
        if (!class_exists(Request::class)) {
270
            return null;
271
        }
272
 
273
        return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
274
            'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
275
            'SCRIPT_NAME' => $this->context->getBaseUrl(),
276
        ]);
277
    }
278
}