-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorNormalizer.php
More file actions
96 lines (81 loc) · 2.77 KB
/
Copy pathErrorNormalizer.php
File metadata and controls
96 lines (81 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\JsonApi\Serializer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Converts {@see \Exception} or {@see FlattenException} or to a JSON API error representation.
*
* @author Héctor Hurtarte <hectorh30@gmail.com>
*/
final class ErrorNormalizer implements NormalizerInterface
{
public const FORMAT = 'jsonapi';
public function __construct(private ?NormalizerInterface $itemNormalizer = null)
{
}
/**
* {@inheritdoc}
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
$jsonApiObject = $this->itemNormalizer->normalize($data, $format, $context);
$error = $jsonApiObject['data']['attributes'] ?? [];
$error['id'] = $jsonApiObject['data']['id'];
if (isset($error['type'])) {
$error['links'] = ['type' => $error['type']];
}
if (!isset($error['code']) && method_exists($data, 'getId')) {
$error['code'] = $data->getId();
}
if (isset($error['status'])) {
$error['status'] = (string) $error['status'];
}
if (!isset($error['violations'])) {
return ['errors' => [$error]];
}
$errors = [];
foreach ($error['violations'] as $violation) {
$e = ['detail' => $violation['message']] + $error;
if (isset($error['links']['type'])) {
$type = $error['links']['type'];
$e['links']['type'] = \sprintf('%s/%s', $type, $violation['propertyPath']);
$e['id'] = str_replace($type, $e['links']['type'], $e['id']);
}
if (isset($e['code'])) {
$e['code'] = \sprintf('%s/%s', $error['code'], $violation['propertyPath']);
}
unset($e['violations']);
$errors[] = $e;
}
return ['errors' => $errors];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return self::FORMAT === $format && ($data instanceof \Exception || $data instanceof FlattenException);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array
{
if (self::FORMAT === $format) {
return [
\Exception::class => true,
FlattenException::class => true,
];
}
return [];
}
}