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