forked from ezsystems/ezpublish-kernel
/
UrlAliasRouter.php
417 lines (370 loc) · 15 KB
/
UrlAliasRouter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
<?php
/**
* File containing the UrlAliasRouter class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\Core\MVC\Symfony\Routing;
use eZ\Publish\API\Repository\LocationService;
use eZ\Publish\API\Repository\URLAliasService;
use eZ\Publish\API\Repository\ContentService;
use eZ\Publish\API\Repository\Values\Content\URLAlias;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Values\Content\Location;
use eZ\Publish\Core\MVC\Symfony\View\Manager as ViewManager;
use eZ\Publish\Core\MVC\Symfony\Routing\Generator\UrlAliasGenerator;
use Symfony\Cmf\Component\Routing\ChainedRouterInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route as SymfonyRoute;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use InvalidArgumentException;
use LogicException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class UrlAliasRouter implements ChainedRouterInterface, RequestMatcherInterface
{
const URL_ALIAS_ROUTE_NAME = 'ez_urlalias';
/**
* @deprecated since 6.0.0.
*/
const LOCATION_VIEW_CONTROLLER = 'ez_content:viewLocation';
/**
* @since 6.0.0
*/
const VIEW_ACTION = 'ez_content:viewAction';
/**
* @var \Symfony\Component\Routing\RequestContext
*/
protected $requestContext;
/**
* @var \eZ\Publish\API\Repository\LocationService
*/
protected $locationService;
/**
* @var \eZ\Publish\API\Repository\URLAliasService
*/
protected $urlAliasService;
/**
* @var \eZ\Publish\API\Repository\ContentService
*/
protected $contentService;
/**
* @var \eZ\Publish\Core\MVC\Symfony\Routing\Generator\UrlAliasGenerator
*/
protected $generator;
/**
* Holds current root Location id.
*
* @var int|string
*/
protected $rootLocationId;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
public function __construct(
LocationService $locationService,
URLAliasService $urlAliasService,
ContentService $contentService,
UrlAliasGenerator $generator,
RequestContext $requestContext,
LoggerInterface $logger = null
) {
$this->locationService = $locationService;
$this->urlAliasService = $urlAliasService;
$this->contentService = $contentService;
$this->generator = $generator;
$this->requestContext = $requestContext !== null ? $requestContext : new RequestContext();
$this->logger = $logger;
}
/**
* Injects current root Location id.
*
* @param int|string $rootLocationId
*/
public function setRootLocationId($rootLocationId)
{
$this->rootLocationId = $rootLocationId;
}
/**
* Tries to match a request with a set of routes.
*
* If the matcher can not find information, it must throw one of the exceptions documented
* below.
*
* @param Request $request The request to match
*
* @return array An array of parameters
*
* @throws \Symfony\Component\Routing\Exception\ResourceNotFoundException If no matching resource could be found
*/
public function matchRequest(Request $request)
{
try {
$requestedPath = $request->attributes->get('semanticPathinfo', $request->getPathInfo());
$urlAlias = $this->getUrlAlias($requestedPath);
if ($this->rootLocationId === null) {
$pathPrefix = '/';
} else {
$pathPrefix = $this->generator->getPathPrefixByRootLocationId($this->rootLocationId);
}
$params = array(
'_route' => self::URL_ALIAS_ROUTE_NAME,
);
switch ($urlAlias->type) {
case URLAlias::LOCATION:
$location = $this->generator->loadLocation($urlAlias->destination);
$params += array(
'_controller' => static::VIEW_ACTION,
'contentId' => $location->contentId,
'locationId' => $urlAlias->destination,
'viewType' => ViewManager::VIEW_TYPE_FULL,
'layout' => true,
);
// For Location alias setup 301 redirect to Location's current URL when:
// 1. alias is history
// 2. alias is custom with forward flag true
// 3. requested URL is not case-sensitive equal with the one loaded
if ($urlAlias->isHistory === true || ($urlAlias->isCustom === true && $urlAlias->forward === true)) {
$params += array(
'semanticPathinfo' => $this->generate($location),
'needsRedirect' => true,
// Specify not to prepend siteaccess while redirecting when applicable since it would be already present (see UrlAliasGenerator::doGenerate())
'prependSiteaccessOnRedirect' => false,
);
} elseif ($this->needsCaseRedirect($urlAlias, $requestedPath, $pathPrefix)) {
$params += array(
'semanticPathinfo' => $this->removePathPrefix($urlAlias->path, $pathPrefix),
'needsRedirect' => true,
);
if ($urlAlias->destination instanceof Location) {
$params += ['locationId' => $urlAlias->destination->id];
}
}
if (isset($this->logger)) {
$this->logger->info("UrlAlias matched location #{$urlAlias->destination}. Forwarding to ViewController");
}
break;
case URLAlias::RESOURCE:
// In URLAlias terms, "forward" means "redirect".
if ($urlAlias->forward) {
$params += array(
'semanticPathinfo' => '/' . trim($urlAlias->destination, '/'),
'needsRedirect' => true,
);
} elseif ($this->needsCaseRedirect($urlAlias, $requestedPath, $pathPrefix)) {
// Handle case-correction redirect
$params += array(
'semanticPathinfo' => $this->removePathPrefix($urlAlias->path, $pathPrefix),
'needsRedirect' => true,
);
} else {
$params += array(
'semanticPathinfo' => '/' . trim($urlAlias->destination, '/'),
'needsForward' => true,
);
}
break;
case URLAlias::VIRTUAL:
// Handle case-correction redirect
if ($this->needsCaseRedirect($urlAlias, $requestedPath, $pathPrefix)) {
$params += array(
'semanticPathinfo' => $this->removePathPrefix($urlAlias->path, $pathPrefix),
'needsRedirect' => true,
);
} else {
// Virtual aliases should load the Content at homepage URL
$params += array(
'semanticPathinfo' => '/',
'needsForward' => true,
);
}
break;
}
return $params;
} catch (NotFoundException $e) {
throw new ResourceNotFoundException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Removes prefix from path.
*
* Checks for presence of $prefix and removes it from $path if found.
*
* @param string $path
* @param string $prefix
*
* @return string
*/
protected function removePathPrefix($path, $prefix)
{
if ($prefix !== '/' && mb_stripos($path, $prefix) === 0) {
$path = mb_substr($path, mb_strlen($prefix));
}
return $path;
}
/**
* Returns true of false on comparing $urlAlias->path and $path with case sensitivity.
*
* Used to determine if redirect is needed because requested path is case-different
* from the stored one.
*
* @param \eZ\Publish\API\Repository\Values\Content\URLAlias $loadedUrlAlias
* @param string $requestedPath
* @param string $pathPrefix
*
* @return bool
*/
protected function needsCaseRedirect(URLAlias $loadedUrlAlias, $requestedPath, $pathPrefix)
{
// If requested path is excluded from tree root jail, compare it to loaded UrlAlias directly.
if ($this->generator->isUriPrefixExcluded($requestedPath)) {
return strcmp($loadedUrlAlias->path, $requestedPath) !== 0;
}
// Compare loaded UrlAlias with requested path, prefixed with configured path prefix.
return
strcmp(
$loadedUrlAlias->path,
$pathPrefix . ($pathPrefix === '/' ? trim($requestedPath, '/') : rtrim($requestedPath, '/'))
) !== 0
;
}
/**
* Returns the UrlAlias object to use, starting from the request.
*
* @param $pathinfo
*
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if the path does not exist or is not valid for the given language
*
* @return URLAlias
*/
protected function getUrlAlias($pathinfo)
{
return $this->urlAliasService->lookup($pathinfo);
}
/**
* Gets the RouteCollection instance associated with this Router.
*
* @return RouteCollection A RouteCollection instance
*/
public function getRouteCollection()
{
return new RouteCollection();
}
/**
* Generates a URL for a location, from the given parameters.
*
* It is possible to directly pass a Location object as the route name, as the ChainRouter allows it through ChainedRouterInterface.
*
* If $name is a route name, the "location" key in $parameters must be set to a valid eZ\Publish\API\Repository\Values\Content\Location object.
* "locationId" can also be provided.
*
* If the generator is not able to generate the url, it must throw the RouteNotFoundException
* as documented below.
*
* @see UrlAliasRouter::supports()
*
* @param string|\eZ\Publish\API\Repository\Values\Content\Location $name The name of the route or a Location instance
* @param mixed $parameters An array of parameters
* @param int $referenceType The type of reference to be generated (one of the constants)
*
* @throws \LogicException
* @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
* @throws \InvalidArgumentException
*
* @return string The generated URL
*
* @api
*/
public function generate($name, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
// Direct access to Location
if ($name instanceof Location) {
return $this->generator->generate($name, $parameters, $referenceType);
}
// Normal route name
if ($name === self::URL_ALIAS_ROUTE_NAME) {
if (isset($parameters['location']) || isset($parameters['locationId'])) {
// Check if location is a valid Location object
if (isset($parameters['location']) && !$parameters['location'] instanceof Location) {
throw new LogicException(
"When generating an UrlAlias route, 'location' parameter must be a valid eZ\\Publish\\API\\Repository\\Values\\Content\\Location."
);
}
$location = isset($parameters['location']) ? $parameters['location'] : $this->locationService->loadLocation($parameters['locationId']);
unset($parameters['location'], $parameters['locationId'], $parameters['viewType'], $parameters['layout']);
return $this->generator->generate($location, $parameters, $referenceType);
}
if (isset($parameters['contentId'])) {
$contentInfo = $this->contentService->loadContentInfo($parameters['contentId']);
unset($parameters['contentId'], $parameters['viewType'], $parameters['layout']);
if (empty($contentInfo->mainLocationId)) {
throw new LogicException('Cannot generate an UrlAlias route for content without main location.');
}
return $this->generator->generate(
$this->locationService->loadLocation($contentInfo->mainLocationId),
$parameters,
$referenceType
);
}
throw new InvalidArgumentException(
"When generating an UrlAlias route, either 'location', 'locationId' or 'contentId' must be provided."
);
}
throw new RouteNotFoundException('Could not match route');
}
public function setContext(RequestContext $context)
{
$this->requestContext = $context;
$this->generator->setRequestContext($context);
}
public function getContext()
{
return $this->requestContext;
}
/**
* Not supported. Please use matchRequest() instead.
*
* @param $pathinfo
*
* @throws \RuntimeException
*/
public function match($pathinfo)
{
throw new \RuntimeException("The UrlAliasRouter doesn't support the match() method. Please use matchRequest() instead.");
}
/**
* Whether the router supports the thing in $name to generate a route.
*
* This check does not need to look if the specific instance can be
* resolved to a route, only whether the router can generate routes from
* objects of this class.
*
* @param mixed $name The route name or route object
*
* @return bool
*/
public function supports($name)
{
return $name instanceof Location || $name === self::URL_ALIAS_ROUTE_NAME;
}
/**
* @see Symfony\Cmf\Component\Routing\VersatileGeneratorInterface::getRouteDebugMessage()
*/
public function getRouteDebugMessage($name, array $parameters = array())
{
if ($name instanceof RouteObjectInterface) {
return 'Route with key ' . $name->getRouteKey();
}
if ($name instanceof SymfonyRoute) {
return 'Route with pattern ' . $name->getPath();
}
return $name;
}
}