1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sententiaregum project. |
5
|
|
|
* |
6
|
|
|
* (c) Maximilian Bosch <[email protected]> |
7
|
|
|
* (c) Ben Bieler <[email protected]> |
8
|
|
|
* |
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
10
|
|
|
* file that was distributed with this source code. |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
declare(strict_types=1); |
14
|
|
|
|
15
|
|
|
namespace AppBundle\EventListener; |
16
|
|
|
|
17
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
18
|
|
|
use Symfony\Component\HttpFoundation\RedirectResponse; |
19
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; |
20
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
21
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* HTTP listener which handles 404 errors. |
25
|
|
|
* |
26
|
|
|
* If the request is an API request, the JSON will be rendered, but if it's an invalid request against the page, it will |
27
|
|
|
* be redirected to the appropriate hashbang target. |
28
|
|
|
* |
29
|
|
|
* @author Maximilian Bosch <[email protected]> |
30
|
|
|
*/ |
31
|
|
|
class NotFoundResponseListener implements EventSubscriberInterface |
32
|
|
|
{ |
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
*/ |
36
|
|
|
public static function getSubscribedEvents(): array |
37
|
|
|
{ |
38
|
|
|
return [ |
39
|
|
|
KernelEvents::EXCEPTION => 'onKernelException', |
40
|
|
|
]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Exception handler. |
45
|
|
|
* |
46
|
|
|
* @param GetResponseForExceptionEvent $event |
47
|
|
|
*/ |
48
|
|
|
public function onKernelException(GetResponseForExceptionEvent $event) |
49
|
|
|
{ |
50
|
|
|
$request = $event->getRequest(); |
51
|
|
|
$uri = $request->getRequestUri(); |
52
|
|
|
|
53
|
|
|
// abort for API requests (fos_rest will take over) and non-404 exceptions |
54
|
|
|
if (!$event->getException() instanceof NotFoundHttpException |
55
|
|
|
|| (bool) preg_match('/^\/api\/(.*)(\?(.*))?$/', $uri) |
56
|
|
|
) { |
57
|
|
|
return; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
// delegate to hashbangs |
61
|
|
|
$event->setResponse(new RedirectResponse($this->getHashBangURL($uri))); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Transforms the URI into a hashbang url. |
66
|
|
|
* |
67
|
|
|
* @param string $requestUri |
68
|
|
|
* |
69
|
|
|
* @return string |
70
|
|
|
*/ |
71
|
|
|
private function getHashBangURL(string $requestUri): string |
72
|
|
|
{ |
73
|
|
|
// the slash after the `#` is not needed as the request_uri contains it's own slash as prefix |
74
|
|
|
return sprintf('/#%s', $requestUri); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|