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

ProblemExceptionNormalizer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 11
c 2
b 0
f 0
dl 0
loc 26
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A supportsNormalization() 0 7 2
A normalize() 0 11 2
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