1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\ControllerUtil\EventListener; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; |
6
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
7
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Converts Exceptions into Symfony HttpKernel Exceptions. |
11
|
|
|
* |
12
|
|
|
* @author Benjamin Eberlei <[email protected]> |
13
|
|
|
* @author Kevin Bond <[email protected]> |
14
|
|
|
* |
15
|
|
|
* @see https://github.com/QafooLabs/QafooLabsNoFrameworkBundle |
16
|
|
|
*/ |
17
|
|
|
class ConvertExceptionListener |
18
|
|
|
{ |
19
|
|
|
private $exceptionClassMap; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param array $exceptionClassMap Class as the key, HTTP status code as the value |
23
|
|
|
*/ |
24
|
2 |
|
public function __construct(array $exceptionClassMap = array()) |
25
|
|
|
{ |
26
|
2 |
|
$this->exceptionClassMap = $exceptionClassMap; |
27
|
2 |
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param GetResponseForExceptionEvent $event |
31
|
|
|
*/ |
32
|
2 |
|
public function onKernelException(GetResponseForExceptionEvent $event) |
33
|
|
|
{ |
34
|
2 |
|
$exception = $event->getException(); |
35
|
|
|
|
36
|
2 |
|
if ($exception instanceof HttpExceptionInterface) { |
37
|
1 |
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
$statusCode = $this->findStatusCode($exception); |
41
|
|
|
|
42
|
2 |
|
if (null === $statusCode) { |
43
|
2 |
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
$event->setException(new HttpException($statusCode, null, $exception)); |
47
|
1 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param \Exception $exception |
51
|
|
|
* |
52
|
|
|
* @return int|null |
53
|
|
|
*/ |
54
|
2 |
|
private function findStatusCode(\Exception $exception) |
55
|
|
|
{ |
56
|
2 |
|
$exceptionClass = get_class($exception); |
57
|
|
|
|
58
|
2 |
|
foreach ($this->exceptionClassMap as $originalExceptionClass => $statusCode) { |
59
|
1 |
|
if ($exceptionClass === $originalExceptionClass || is_subclass_of($exceptionClass, $originalExceptionClass)) { |
60
|
1 |
|
return (int) $statusCode; |
61
|
|
|
} |
62
|
2 |
|
} |
63
|
|
|
|
64
|
2 |
|
return null; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|