|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Palmtree\CanonicalUrlBundle\EventListener; |
|
4
|
|
|
|
|
5
|
|
|
use Palmtree\CanonicalUrlBundle\Service\CanonicalUrlGenerator; |
|
6
|
|
|
use Symfony\Component\HttpFoundation\RedirectResponse; |
|
7
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
|
8
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; |
|
9
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
|
10
|
|
|
use Symfony\Component\Routing\Exception\ResourceNotFoundException; |
|
11
|
|
|
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
|
12
|
|
|
use Symfony\Component\Routing\RouterInterface; |
|
13
|
|
|
|
|
14
|
|
|
class RequestListener |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var CanonicalUrlGenerator */ |
|
17
|
|
|
protected $urlGenerator; |
|
18
|
|
|
/** @var bool */ |
|
19
|
|
|
protected $redirect; |
|
20
|
|
|
/** @var int */ |
|
21
|
|
|
protected $redirectCode; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* KernelEventListener constructor. |
|
25
|
|
|
* @param CanonicalUrlGenerator $urlGenerator |
|
26
|
|
|
* @param array $config |
|
27
|
|
|
*/ |
|
28
|
3 |
|
public function __construct(CanonicalUrlGenerator $urlGenerator, array $config = []) |
|
29
|
|
|
{ |
|
30
|
3 |
|
$this->urlGenerator = $urlGenerator; |
|
31
|
|
|
|
|
32
|
3 |
|
$this->redirect = $config['redirect']; |
|
33
|
3 |
|
$this->redirectCode = $config['redirect_code']; |
|
34
|
3 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Listener for the 'kernel.request' event. |
|
38
|
|
|
* |
|
39
|
|
|
* @param GetResponseEvent $event |
|
40
|
|
|
* |
|
41
|
|
|
* @return bool |
|
42
|
|
|
*/ |
|
43
|
3 |
|
public function onKernelRequest(GetResponseEvent $event) |
|
44
|
|
|
{ |
|
45
|
3 |
|
$request = $event->getRequest(); |
|
46
|
|
|
|
|
47
|
3 |
|
$route = $request->attributes->get('_route'); |
|
48
|
|
|
|
|
49
|
3 |
|
if (!$route) { |
|
50
|
1 |
|
return false; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
2 |
|
$params = $request->attributes->get('_route_params'); |
|
54
|
|
|
|
|
55
|
|
|
// Get full request URL without query string. |
|
56
|
2 |
|
$requestUrl = $request->getSchemeAndHttpHost() . $request->getRequestUri(); |
|
57
|
2 |
|
$requestUrl = urldecode(strtok($requestUrl, '?')); |
|
58
|
|
|
|
|
59
|
2 |
|
$redirectUrl = $this->urlGenerator->generate($route, $params); |
|
60
|
|
|
// Compare without query string |
|
61
|
2 |
|
$canonicalUrl = urldecode(strtok($redirectUrl, '?')); |
|
62
|
|
|
|
|
63
|
2 |
|
if ($redirectUrl && strcasecmp($requestUrl, $canonicalUrl) !== 0) { |
|
64
|
1 |
|
if ($this->redirect) { |
|
65
|
1 |
|
$response = new RedirectResponse($redirectUrl, $this->redirectCode); |
|
66
|
1 |
|
$event->setResponse($response); |
|
67
|
|
|
|
|
68
|
1 |
|
return true; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
1 |
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|