Skip to content

Commit 7643871

Browse files
author
Marcus Stöhr
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 7643871

File tree

2 files changed

+268
-0
lines changed

2 files changed

+268
-0
lines changed

src/JsonApi/Serializer/ErrorNormalizer.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,25 @@ 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'])) {
4150
$error['links'] = ['type' => $error['type']];
4251
}
4352

53+
if (isset($error['status'])) {
54+
$error['status'] = (string) $error['status'];
55+
}
56+
4457
if (!isset($error['code']) && method_exists($object, 'getId')) {
4558
$error['code'] = $object->getId();
4659
}
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
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+
public function testNormalizeConvertsIntegerStatusToString(): void
83+
{
84+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
85+
$itemNormalizer->method('normalize')->willReturn([
86+
'data' => [
87+
'type' => 'errors',
88+
'id' => 'error-500',
89+
'attributes' => [
90+
'title' => 'Internal Server Error',
91+
'detail' => 'An error occurred',
92+
'status' => 500,
93+
],
94+
],
95+
]);
96+
97+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
98+
$result = $errorNormalizer->normalize(new \Exception('Error'), 'jsonapi');
99+
100+
$this->assertArrayHasKey('errors', $result);
101+
$this->assertIsString($result['errors'][0]['status'], 'JSON:API requires status to be a string');
102+
$this->assertEquals('500', $result['errors'][0]['status']);
103+
}
104+
105+
/**
106+
* Test with violations in the error attributes.
107+
*/
108+
public function testNormalizeWithViolations(): void
109+
{
110+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
111+
$itemNormalizer->method('normalize')->willReturn([
112+
'data' => [
113+
'type' => 'errors',
114+
'id' => 'validation-error',
115+
'attributes' => [
116+
'title' => 'Validation failed',
117+
'detail' => 'Invalid input',
118+
'status' => 422,
119+
'violations' => [
120+
[
121+
'message' => 'This field is required',
122+
'propertyPath' => 'name',
123+
],
124+
[
125+
'message' => 'Invalid email format',
126+
'propertyPath' => 'email',
127+
],
128+
],
129+
],
130+
],
131+
]);
132+
133+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
134+
$result = $errorNormalizer->normalize(new \Exception('Validation error'), 'jsonapi');
135+
136+
$this->assertArrayHasKey('errors', $result);
137+
$this->assertCount(2, $result['errors']);
138+
$this->assertEquals('This field is required', $result['errors'][0]['detail']);
139+
$this->assertEquals('Invalid email format', $result['errors'][1]['detail']);
140+
$this->assertFalse(isset($result['errors'][0]['violations']));
141+
$this->assertIsString($result['errors'][0]['status'], 'JSON:API requires status to be a string');
142+
$this->assertEquals('422', $result['errors'][0]['status']);
143+
}
144+
145+
/**
146+
* Test with type and links generation.
147+
*/
148+
public function testNormalizeWithTypeGeneratesLinks(): void
149+
{
150+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
151+
$itemNormalizer->method('normalize')->willReturn([
152+
'data' => [
153+
'type' => 'errors',
154+
'id' => 'about:blank/errors/validation',
155+
'attributes' => [
156+
'type' => 'about:blank/errors/validation',
157+
'title' => 'Validation Error',
158+
'detail' => 'Input validation failed',
159+
'status' => '422',
160+
'violations' => [
161+
[
162+
'message' => 'Must be a number',
163+
'propertyPath' => 'age',
164+
],
165+
],
166+
],
167+
],
168+
]);
169+
170+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
171+
$result = $errorNormalizer->normalize(new \Exception('Validation'), 'jsonapi');
172+
173+
$this->assertArrayHasKey('errors', $result);
174+
$this->assertCount(1, $result['errors']);
175+
$this->assertArrayHasKey('links', $result['errors'][0]);
176+
$this->assertStringContainsString('age', $result['errors'][0]['links']['type']);
177+
}
178+
179+
public function testJsonApiComplianceForMissingAttributesCase(): void
180+
{
181+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
182+
$itemNormalizer->method('normalize')->willReturn([
183+
'data' => [
184+
'id' => 'error-123',
185+
'type' => 'errors',
186+
],
187+
]);
188+
189+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
190+
$result = $errorNormalizer->normalize(new \Exception('Not found'), 'jsonapi');
191+
192+
$this->assertArrayHasKey('errors', $result, 'Response must have "errors" key at top level');
193+
$this->assertIsArray($result['errors'], '"errors" must be an array');
194+
$this->assertNotEmpty($result['errors'], '"errors" array must not be empty');
195+
196+
$error = $result['errors'][0];
197+
$this->assertIsArray($error, 'Each error must be an object/array');
198+
199+
$hasAtLeastOneMember = isset($error['id']) || isset($error['links']) || isset($error['status'])
200+
|| isset($error['code']) || isset($error['title']) || isset($error['detail'])
201+
|| isset($error['source']) || isset($error['meta']);
202+
203+
$this->assertTrue($hasAtLeastOneMember, 'Error object must contain at least one of: id, links, status, code, title, detail, source, meta');
204+
205+
if (isset($error['status'])) {
206+
$this->assertIsString($error['status'], '"status" must be a string value');
207+
}
208+
209+
if (isset($error['code'])) {
210+
$this->assertIsString($error['code'], '"code" must be a string value');
211+
}
212+
213+
if (isset($error['links'])) {
214+
$this->assertIsArray($error['links'], '"links" must be an object');
215+
}
216+
}
217+
218+
public function testJsonApiComplianceForNormalCase(): void
219+
{
220+
$itemNormalizer = $this->createMock(NormalizerInterface::class);
221+
$itemNormalizer->method('normalize')->willReturn([
222+
'data' => [
223+
'type' => 'errors',
224+
'id' => 'error-456',
225+
'attributes' => [
226+
'title' => 'Validation Failed',
227+
'detail' => 'The request body is invalid',
228+
'status' => '422',
229+
'code' => 'validation_error',
230+
],
231+
],
232+
]);
233+
234+
$errorNormalizer = new ErrorNormalizer($itemNormalizer);
235+
$result = $errorNormalizer->normalize(new \Exception('Validation error'), 'jsonapi');
236+
237+
$this->assertArrayHasKey('errors', $result);
238+
$this->assertIsArray($result['errors']);
239+
240+
$error = $result['errors'][0];
241+
$this->assertIsArray($error);
242+
243+
$hasAtLeastOneMember = isset($error['id']) || isset($error['links']) || isset($error['status'])
244+
|| isset($error['code']) || isset($error['title']) || isset($error['detail'])
245+
|| isset($error['source']) || isset($error['meta']);
246+
247+
$this->assertTrue($hasAtLeastOneMember, 'Error object must contain at least one required member');
248+
249+
$this->assertEquals('error-456', $error['id']);
250+
$this->assertEquals('Validation Failed', $error['title']);
251+
$this->assertEquals('The request body is invalid', $error['detail']);
252+
$this->assertEquals('422', $error['status']);
253+
$this->assertEquals('validation_error', $error['code']);
254+
}
255+
}

0 commit comments

Comments
 (0)