Completed
Push — master ( 60f475...6caaad )
by Maximilian
03:33
created

NotFoundResponseListener   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
c 0
b 0
f 0
lcom 0
cbo 3
dl 0
loc 46
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 6 1
A onKernelException() 0 15 3
A getHashBangURL() 0 5 1
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