Passed
Pull Request — main (#56)
by Niels
01:54
created

supportsNormalization()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the OpenapiBundle package.
7
 *
8
 * (c) Niels Nijens <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Nijens\OpenapiBundle\ExceptionHandling\Normalizer;
15
16
use Nijens\OpenapiBundle\ExceptionHandling\Exception\ProblemExceptionInterface;
17
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
18
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
19
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
20
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
21
use Throwable;
22
23
/**
24
 * Normalizes a {@see Throwable} implementing the {@see ProblemExceptionInterface}.
25
 *
26
 * @author Niels Nijens <[email protected]>
27
 */
28
class ProblemExceptionNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
29
{
30
    use NormalizerAwareTrait;
31
32
    private const ALREADY_CALLED = 'nijens_openapi.problem_exception_normalizer.already_called';
33
34
    public function normalize($object, $format = null, array $context = [])
35
    {
36
        if ($object instanceof ProblemExceptionInterface === false) {
37
            throw new InvalidArgumentException(sprintf('The object must implement "%s".', ProblemExceptionInterface::class));
38
        }
39
40
        $context[self::ALREADY_CALLED] = true;
41
42
        $data = $this->normalizer->normalize($object, $format, $context);
43
44
        return array_filter($data);
45
    }
46
47
    public function supportsNormalization($data, $format = null, array $context = []): bool
48
    {
49
        if (isset($context[self::ALREADY_CALLED])) {
50
            return false;
51
        }
52
53
        return $data instanceof ProblemExceptionInterface;
54
    }
55
}
56