Completed
Pull Request — master (#1036)
by Hector
03:15
created

ErrorNormalizer::normalize()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 25
Code Lines 14

Duplication

Lines 9
Ratio 36 %

Importance

Changes 0
Metric Value
dl 9
loc 25
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 8
nop 3
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\JsonApi\Serializer;
15
16
use Symfony\Component\Debug\Exception\FlattenException;
17
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
18
19
final class ErrorNormalizer implements NormalizerInterface
20
{
21
    const FORMAT = 'jsonapi';
22
23
    private $debug;
24
25
    public function __construct(bool $debug = false)
26
    {
27
        $this->debug = $debug;
28
    }
29
30
    public function normalize($object, $format = null, array $context = [])
31
    {
32
        $message = $object->getMessage();
33
34 View Code Duplication
        if ($this->debug) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
            $trace = $object->getTrace();
36
        } elseif ($object instanceof FlattenException) {
37
            $statusCode = $context['statusCode'] ?? $object->getStatusCode();
38
39
            if ($statusCode >= 500 && $statusCode < 600) {
40
                $message = Response::$statusTexts[$statusCode];
41
            }
42
        }
43
44
        $data = [
45
            'title' => $context['title'] ?? 'An error occurred',
46
            'description' => $message ?? (string) $object,
47
        ];
48
49
        if (isset($trace)) {
50
            $data['trace'] = $trace;
51
        }
52
53
        return $data;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function supportsNormalization($data, $format = null)
60
    {
61
        return self::FORMAT === $format && ($data instanceof \Exception || $data instanceof FlattenException);
62
    }
63
}
64