1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Faecie\Bundle\JsonApiErrorResponseBundle\SerializerHandler; |
6
|
|
|
|
7
|
|
|
use Error; |
8
|
|
|
use Exception; |
9
|
|
|
use Faecie\Bundle\JsonApiErrorResponseBundle\Enum\ErrorCodesEnum; |
10
|
|
|
use Faecie\Bundle\JsonApiErrorResponseBundle\ExceptionDescriber\ExceptionDescriberInterface; |
11
|
|
|
use Faecie\Bundle\JsonApiErrorResponseBundle\JsonApi\Error as JsonApiError; |
12
|
|
|
use JMS\Serializer\Context; |
13
|
|
|
use JMS\Serializer\GraphNavigator; |
14
|
|
|
use JMS\Serializer\Handler\SubscribingHandlerInterface; |
15
|
|
|
use JMS\Serializer\JsonSerializationVisitor; |
16
|
|
|
use Throwable; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class JmsExceptionNormalizer |
20
|
|
|
*/ |
21
|
|
|
class JmsExceptionNormalizer implements SubscribingHandlerInterface |
22
|
|
|
{ |
23
|
|
|
private $exceptionDescriber; |
24
|
|
|
|
25
|
2 |
|
public function __construct(ExceptionDescriberInterface $describer) |
26
|
|
|
{ |
27
|
2 |
|
$this->exceptionDescriber = $describer; |
28
|
2 |
|
} |
29
|
|
|
|
30
|
1 |
|
public static function getSubscribingMethods() |
31
|
|
|
{ |
32
|
|
|
return [ |
33
|
|
|
[ |
34
|
1 |
|
'direction' => GraphNavigator::DIRECTION_SERIALIZATION, |
35
|
1 |
|
'format' => 'json', |
36
|
|
|
'type' => Exception::class, |
37
|
1 |
|
'method' => 'serializeToJson', |
38
|
|
|
], |
39
|
|
|
[ |
40
|
1 |
|
'direction' => GraphNavigator::DIRECTION_SERIALIZATION, |
41
|
1 |
|
'format' => 'json', |
42
|
|
|
'type' => Error::class, |
43
|
1 |
|
'method' => 'serializeToJson', |
44
|
|
|
], |
45
|
|
|
]; |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
public function serializeToJson( |
49
|
|
|
JsonSerializationVisitor $visitor, |
50
|
|
|
Throwable $exception, |
51
|
|
|
array $type, |
52
|
|
|
Context $context |
53
|
|
|
): iterable { |
54
|
2 |
|
return $visitor->visitArray($this->getInformation($exception), $type, $context); |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
private function getInformation(Throwable $exception): array |
58
|
|
|
{ |
59
|
|
|
|
60
|
2 |
|
$errors = $this->exceptionDescriber->extractErrors($exception); |
61
|
|
|
|
62
|
2 |
|
if (! empty($errors)) { |
63
|
1 |
|
return ['errors' => $errors]; |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
return ['errors' => [new JsonApiError(ErrorCodesEnum::INTERNAL)]]; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|