JmsExceptionNormalizer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 48
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribingMethods() 0 17 1
A serializeToJson() 0 8 1
A getInformation() 0 11 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