Completed
Push — master ( aaddfb...c1a2e8 )
by Tobias
05:53
created

ExceptionListener::onKernelException()   D

Complexity

Conditions 10
Paths 8

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 0
cts 27
cp 0
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 22
nc 8
nop 1
crap 110

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Happyr\ApiBundle\EventListener;
4
5
use Fervo\ValidatedMessage\ValidationFailedException;
6
use Happyr\ApiBundle\Service\ResponseFactory;
7
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
8
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
9
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
10
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
11
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
12
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
13
use Symfony\Component\Security\Core\Exception\AuthenticationException;
14
use Symfony\Component\Validator\ConstraintViolationInterface;
15
16
/**
17
 * @author Tobias Nyholm <[email protected]>
18
 */
19
class ExceptionListener
20
{
21
    /**
22
     * @var ResponseFactory
23
     */
24
    private $responseFactory;
25
26
    /**
27
     * @var string
28
     */
29
    private $pathPrefix;
30
31
    /**
32
     * @param ResponseFactory $responseFactory
33
     * @param string          $pathPrefix
34
     */
35
    public function __construct(ResponseFactory $responseFactory, $pathPrefix)
36
    {
37
        $this->responseFactory = $responseFactory;
38
        $this->pathPrefix = $pathPrefix;
39
    }
40
41
    /**
42
     * Make sure we print a nice error message to the user when we encounter an exception.
43
     *
44
     * @param GetResponseForExceptionEvent $event
45
     */
46
    public function onKernelException(GetResponseForExceptionEvent $event)
47
    {
48
        // Make sure to match uri before we start to catch exceptions
49
        if (!preg_match('|^'.$this->pathPrefix.'.*|sim', $event->getRequest()->getPathInfo())) {
50
            return;
51
        }
52
53
        $exception = $event->getException();
54
        if ($exception instanceof AccessDeniedException) {
55
            $response = $this->responseFactory->createForbidden();
56
        } elseif ($exception instanceof AuthenticationException) {
57
            $response = $this->responseFactory->createUnauthorized();
58
        } elseif ($exception instanceof BadRequestHttpException) {
59
            $response = $this->responseFactory->createWrongArgs();
60
        } elseif ($exception instanceof MethodNotAllowedException || $exception instanceof MethodNotAllowedHttpException) {
61
            $response = $this->responseFactory->createWithError('Method not allowed', 405, 'GEN-METHOD');
62
        } elseif ($exception instanceof NotFoundHttpException) {
63
            $response = $this->responseFactory->createNotFound();
64
        } elseif ($exception instanceof ValidationFailedException) {
65
            $message = '';
66
            /** @var ConstraintViolationInterface $violation */
67
            foreach ($exception->getViolations() as $violation) {
68
                $message .= sprintf('%s: %s ', $violation->getPropertyPath(), $violation->getMessage());
69
            }
70
71
            $response = $this->responseFactory->createWrongArgs($message);
72
        } else {
73
            $response = $this->responseFactory->createInternalError();
74
        }
75
76
        $event->setResponse($response);
77
    }
78
}
79