Completed
Push — master ( 8b213d...979520 )
by Kévin
05:20 queued 02:18
created

ErrorNormalizer::normalize()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
cc 6
eloc 16
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
namespace ApiPlatform\Core\Hydra\Serializer;
13
14
use ApiPlatform\Core\Api\UrlGeneratorInterface;
15
use Symfony\Component\Debug\Exception\FlattenException;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
18
19
/**
20
 * Converts {@see \Exception} or {@see \Symfony\Component\Debug\Exception\FlattenException} to a Hydra error representation.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 * @author Samuel ROZE <[email protected]>
24
 */
25
final class ErrorNormalizer implements NormalizerInterface
26
{
27
    const FORMAT = 'jsonld';
28
29
    private $urlGenerator;
30
    private $debug;
31
32
    public function __construct(UrlGeneratorInterface $urlGenerator, bool $debug = false)
33
    {
34
        $this->urlGenerator = $urlGenerator;
35
        $this->debug = $debug;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function normalize($object, $format = null, array $context = [])
42
    {
43
        $message = $object->getMessage();
44
        if ($this->debug) {
45
            $trace = $object->getTrace();
46
        } elseif ($object instanceof FlattenException) {
47
            $statusCode = $context['statusCode'] ?? $object->getStatusCode();
48
            if ($statusCode >= 500 && $statusCode < 600) {
49
                $message = Response::$statusTexts[$statusCode];
50
            }
51
        }
52
53
        $data = [
54
            '@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Error']),
55
            '@type' => 'hydra:Error',
56
            'hydra:title' => $context['title'] ?? 'An error occurred',
57
            'hydra:description' => $message ?? (string) $object,
58
        ];
59
60
        if (isset($trace)) {
61
            $data['trace'] = $trace;
62
        }
63
64
        return $data;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function supportsNormalization($data, $format = null)
71
    {
72
        return self::FORMAT === $format && ($data instanceof \Exception || $data instanceof FlattenException);
73
    }
74
}
75