Skip to content

Commit 918e2fd

Browse files
committed
fix(jsonapi): handle missing attributes in ErrorNormalizer
Fixes undefined array key warning when normalizing exceptions that don't have attributes in their normalized structure. This typically occurs with ItemNotFoundException when invalid resource identifiers are provided.
1 parent 028325b commit 918e2fd

File tree

2 files changed

+241
-0
lines changed

2 files changed

+241
-0
lines changed

src/JsonApi/Serializer/ErrorNormalizer.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ public function __construct(private ?NormalizerInterface $itemNormalizer = null)
3535
public function normalize(mixed $object, ?string $format = null, array $context = []): array
3636
{
3737
$jsonApiObject = $this->itemNormalizer->normalize($object, $format, $context);
38+
39+
if (!isset($jsonApiObject['data']['attributes'])) {
40+
return ['errors' => [[
41+
'id' => $jsonApiObject['data']['id'] ?? uniqid('error_', true),
42+
'status' => (string) (method_exists($object, 'getStatusCode') ? $object->getStatusCode() : 500),
43+
'title' => method_exists($object, 'getMessage') ? $object->getMessage() : 'An error occurred',
44+
]]];
45+
}
46+
3847
$error = $jsonApiObject['data']['attributes'];
3948
$error['id'] = $jsonApiObject['data']['id'];
4049
if (isset($error['type'])) {
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
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\Tests\JsonApi\Serializer;
15+
16+
use ApiPlatform\JsonApi\Serializer\ErrorNormalizer;
17+
use PHPUnit\Framework\TestCase;
18+
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
19+
20+
/**
21+
* Tests for the JSON API ErrorNormalizer.
22+
*/
23+
final class ErrorNormalizerTest extends TestCase
24+
{
25+
/**
26+
* Test normalization when attributes are missing from the normalized structure.
27+
* This can occur with ItemNotFoundException or similar exceptions.
28+
* The normalizer should handle this gracefully and return a valid JSON:API error.
29+
*/
30+
public function testNormalizeWithMissingAttributes(): void
31+
{
32+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
33+
$itemNormalizer->method('normalize')->willReturn([
34+
'data' => [
35+
'id' => 'error-1',
36+
'type' => 'errors',
37+
],
38+
]);
39+
40+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
41+
$exception = new \Exception('Test error');
42+
43+
$result = $errorNormalizer->normalize($exception, 'jsonapi');
44+
45+
$this->assertArrayHasKey('errors', $result);
46+
$this->assertIsArray($result['errors']);
47+
$this->assertCount(1, $result['errors']);
48+
$this->assertEquals('error-1', $result['errors'][0]['id']);
49+
$this->assertEquals('Test error', $result['errors'][0]['title']);
50+
$this->assertArrayHasKey('status', $result['errors'][0]);
51+
}
52+
53+
/**
54+
* Test the normal case with properly structured normalized data.
55+
*/
56+
public function testNormalizeWithValidStructure(): void
57+
{
58+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
59+
$itemNormalizer->method('normalize')->willReturn([
60+
'data' => [
61+
'type' => 'errors',
62+
'id' => 'error-1',
63+
'attributes' => [
64+
'title' => 'An error occurred',
65+
'detail' => 'Something went wrong',
66+
'status' => '500',
67+
],
68+
],
69+
]);
70+
71+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
72+
$result = $errorNormalizer->normalize(new \Exception('Test error'), 'jsonapi');
73+
74+
$this->assertArrayHasKey('errors', $result);
75+
$this->assertCount(1, $result['errors']);
76+
$this->assertEquals('error-1', $result['errors'][0]['id']);
77+
$this->assertEquals('An error occurred', $result['errors'][0]['title']);
78+
$this->assertEquals('Something went wrong', $result['errors'][0]['detail']);
79+
$this->assertIsString($result['errors'][0]['status']);
80+
}
81+
82+
/**
83+
* Test with violations in the error attributes.
84+
*/
85+
public function testNormalizeWithViolations(): void
86+
{
87+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
88+
$itemNormalizer->method('normalize')->willReturn([
89+
'data' => [
90+
'type' => 'errors',
91+
'id' => 'validation-error',
92+
'attributes' => [
93+
'title' => 'Validation failed',
94+
'detail' => 'Invalid input',
95+
'status' => 422,
96+
'violations' => [
97+
[
98+
'message' => 'This field is required',
99+
'propertyPath' => 'name',
100+
],
101+
[
102+
'message' => 'Invalid email format',
103+
'propertyPath' => 'email',
104+
],
105+
],
106+
],
107+
],
108+
]);
109+
110+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
111+
$result = $errorNormalizer->normalize(new \Exception('Validation error'), 'jsonapi');
112+
113+
$this->assertArrayHasKey('errors', $result);
114+
$this->assertCount(2, $result['errors']);
115+
$this->assertEquals('This field is required', $result['errors'][0]['detail']);
116+
$this->assertEquals('Invalid email format', $result['errors'][1]['detail']);
117+
$this->assertFalse(isset($result['errors'][0]['violations']));
118+
$this->assertIsInt($result['errors'][0]['status']);
119+
$this->assertEquals(422, $result['errors'][0]['status']);
120+
}
121+
122+
/**
123+
* Test with type and links generation.
124+
*/
125+
public function testNormalizeWithTypeGeneratesLinks(): void
126+
{
127+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
128+
$itemNormalizer->method('normalize')->willReturn([
129+
'data' => [
130+
'type' => 'errors',
131+
'id' => 'about:blank/errors/validation',
132+
'attributes' => [
133+
'type' => 'about:blank/errors/validation',
134+
'title' => 'Validation Error',
135+
'detail' => 'Input validation failed',
136+
'status' => '422',
137+
'violations' => [
138+
[
139+
'message' => 'Must be a number',
140+
'propertyPath' => 'age',
141+
],
142+
],
143+
],
144+
],
145+
]);
146+
147+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
148+
$result = $errorNormalizer->normalize(new \Exception('Validation'), 'jsonapi');
149+
150+
$this->assertArrayHasKey('errors', $result);
151+
$this->assertCount(1, $result['errors']);
152+
$this->assertArrayHasKey('links', $result['errors'][0]);
153+
$this->assertStringContainsString('age', $result['errors'][0]['links']['type']);
154+
}
155+
156+
public function testJsonApiComplianceForMissingAttributesCase(): void
157+
{
158+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
159+
$itemNormalizer->method('normalize')->willReturn([
160+
'data' => [
161+
'id' => 'error-123',
162+
'type' => 'errors',
163+
],
164+
]);
165+
166+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
167+
$result = $errorNormalizer->normalize(new \Exception('Not found'), 'jsonapi');
168+
169+
$this->assertArrayHasKey('errors', $result, 'Response must have "errors" key at top level');
170+
$this->assertIsArray($result['errors'], '"errors" must be an array');
171+
$this->assertNotEmpty($result['errors'], '"errors" array must not be empty');
172+
173+
$error = $result['errors'][0];
174+
$this->assertIsArray($error, 'Each error must be an object/array');
175+
176+
$hasAtLeastOneMember = isset($error['id']) || isset($error['links']) || isset($error['status'])
177+
|| isset($error['code']) || isset($error['title']) || isset($error['detail'])
178+
|| isset($error['source']) || isset($error['meta']);
179+
180+
$this->assertTrue($hasAtLeastOneMember, 'Error object must contain at least one of: id, links, status, code, title, detail, source, meta');
181+
182+
if (isset($error['status'])) {
183+
$this->assertIsString($error['status'], '"status" must be a string value');
184+
}
185+
186+
if (isset($error['code'])) {
187+
$this->assertIsString($error['code'], '"code" must be a string value');
188+
}
189+
190+
if (isset($error['links'])) {
191+
$this->assertIsArray($error['links'], '"links" must be an object');
192+
}
193+
}
194+
195+
public function testJsonApiComplianceForNormalCase(): void
196+
{
197+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
198+
$itemNormalizer->method('normalize')->willReturn([
199+
'data' => [
200+
'type' => 'errors',
201+
'id' => 'error-456',
202+
'attributes' => [
203+
'title' => 'Validation Failed',
204+
'detail' => 'The request body is invalid',
205+
'status' => '422',
206+
'code' => 'validation_error',
207+
],
208+
],
209+
]);
210+
211+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
212+
$result = $errorNormalizer->normalize(new \Exception('Validation error'), 'jsonapi');
213+
214+
$this->assertArrayHasKey('errors', $result);
215+
$this->assertIsArray($result['errors']);
216+
217+
$error = $result['errors'][0];
218+
$this->assertIsArray($error);
219+
220+
$hasAtLeastOneMember = isset($error['id']) || isset($error['links']) || isset($error['status'])
221+
|| isset($error['code']) || isset($error['title']) || isset($error['detail'])
222+
|| isset($error['source']) || isset($error['meta']);
223+
224+
$this->assertTrue($hasAtLeastOneMember, 'Error object must contain at least one required member');
225+
226+
$this->assertEquals('error-456', $error['id']);
227+
$this->assertEquals('Validation Failed', $error['title']);
228+
$this->assertEquals('The request body is invalid', $error['detail']);
229+
$this->assertEquals('422', $error['status']);
230+
$this->assertEquals('validation_error', $error['code']);
231+
}
232+
}

0 commit comments

Comments
 (0)