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\Hydra\Serializer; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Api\UrlGeneratorInterface; |
17
|
|
|
use ApiPlatform\Core\Problem\Serializer\ErrorNormalizerTrait; |
18
|
|
|
use Symfony\Component\Debug\Exception\FlattenException; |
19
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Converts {@see \Exception} or {@see \Symfony\Component\Debug\Exception\FlattenException} to a Hydra error representation. |
23
|
|
|
* |
24
|
|
|
* @author Kévin Dunglas <[email protected]> |
25
|
|
|
* @author Samuel ROZE <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class ErrorNormalizer implements NormalizerInterface |
28
|
|
|
{ |
29
|
|
|
const FORMAT = 'jsonld'; |
30
|
|
|
|
31
|
|
|
use ErrorNormalizerTrait; |
32
|
|
|
|
33
|
|
|
private $urlGenerator; |
34
|
|
|
private $debug; |
35
|
|
|
|
36
|
|
|
public function __construct(UrlGeneratorInterface $urlGenerator, bool $debug = false) |
37
|
|
|
{ |
38
|
|
|
$this->urlGenerator = $urlGenerator; |
39
|
|
|
$this->debug = $debug; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* {@inheritdoc} |
44
|
|
|
*/ |
45
|
|
|
public function normalize($object, $format = null, array $context = []) |
46
|
|
|
{ |
47
|
|
|
if ($this->debug) { |
48
|
|
|
$trace = $object->getTrace(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$message = $this->getErrorMessage($object, $context, $this->debug); |
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
|
|
|
|