JmsExceptionNormalizer::getInformation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 5
cts 5
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
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