Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/JsonApi/Serializer/ConstraintViolationListNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\JsonApi\Serializer;

use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
Expand All @@ -38,9 +39,13 @@ public function __construct(private readonly PropertyMetadataFactoryInterface $p
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
$operation = $context['operation'] ?? null;
$status = (string) ($operation instanceof HttpOperation ? $operation->getStatus() : null) ?: '422';
$violations = [];
foreach ($data as $violation) {
$violations[] = [
'status' => $status,
'title' => 'Validation Failed',
'detail' => $violation->getMessage(),
'source' => [
'pointer' => $this->getSourcePointerFromViolation($violation),
Expand Down Expand Up @@ -72,13 +77,13 @@ private function getSourcePointerFromViolation(ConstraintViolationInterface $vio
$fieldName = $violation->getPropertyPath();

if (!$fieldName) {
return 'data';
return '/data';
}

$root = $violation->getRoot();

if (!\is_object($root)) {
return "data/attributes/$fieldName";
return "/data/attributes/$fieldName";
}

$class = $root::class;
Expand All @@ -94,9 +99,9 @@ private function getSourcePointerFromViolation(ConstraintViolationInterface $vio
}

if ($propertyMetadata->getNativeType()?->isSatisfiedBy(static fn ($t) => $t instanceof ObjectType)) {
return "data/relationships/$fieldName";
return "/data/relationships/$fieldName";
}

return "data/attributes/$fieldName";
return "/data/attributes/$fieldName";
}
}
20 changes: 15 additions & 5 deletions src/JsonApi/Tests/Serializer/ConstraintViolationNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,27 @@ public function testNormalize(): void
[
'errors' => [
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'This value should not be null.',
'source' => [
'pointer' => 'data/relationships/relatedDummy',
'pointer' => '/data/relationships/relatedDummy',
],
],
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'This value should not be null.',
'source' => [
'pointer' => 'data/attributes/name',
'pointer' => '/data/attributes/name',
],
],
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'Unknown violation.',
'source' => [
'pointer' => 'data',
'pointer' => '/data',
],
],
],
Expand All @@ -111,9 +117,11 @@ public function testNormalizeWithStringRoot(): void
[
'errors' => [
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'Invalid page value.',
'source' => [
'pointer' => 'data/attributes/page',
'pointer' => '/data/attributes/page',
],
],
],
Expand All @@ -140,9 +148,11 @@ public function testNormalizeWithNullRoot(): void
[
'errors' => [
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'Invalid value.',
'source' => [
'pointer' => 'data/attributes/field',
'pointer' => '/data/attributes/field',
],
],
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@
uriTemplate: '/jsonapi_validation_problem',
processor: [self::class, 'processValidation'],
),
new Post(
uriTemplate: '/jsonapi_validation_problem_bad_request',
processor: [self::class, 'processValidation'],
exceptionToStatus: [ValidationException::class => 400],
),
new Post(
uriTemplate: '/jsonapi_exception_problem',
processor: [self::class, 'processBadRequest'],
Expand Down
65 changes: 65 additions & 0 deletions tests/Functional/JsonApi/ErrorObjectMembersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?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\Tests\Functional\JsonApi;

use ApiPlatform\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\JsonApi\ErrorProblem;
use ApiPlatform\Tests\SetupClassResourcesTrait;

final class ErrorObjectMembersTest extends ApiTestCase
{
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

public static function getResources(): array
{
return [ErrorProblem::class];
}

public function testValidationErrorHasStatusAndTitle(): void
{
$response = self::createClient()->request('POST', '/jsonapi_validation_problem', [
'headers' => ['accept' => 'application/vnd.api+json', 'content-type' => 'application/vnd.api+json'],
'json' => ['data' => ['type' => 'JsonApiErrorProblem', 'attributes' => new \stdClass()]],
]);

$this->assertResponseStatusCodeSame(422);
$error = $response->toArray(false)['errors'][0];
$this->assertSame('422', $error['status'] ?? null);
$this->assertArrayHasKey('title', $error);
}

public function testValidationErrorPointerIsAJsonPointer(): void
{
$response = self::createClient()->request('POST', '/jsonapi_validation_problem', [
'headers' => ['accept' => 'application/vnd.api+json', 'content-type' => 'application/vnd.api+json'],
'json' => ['data' => ['type' => 'JsonApiErrorProblem', 'attributes' => new \stdClass()]],
]);

$this->assertResponseStatusCodeSame(422);
$this->assertSame('/data/attributes/name', $response->toArray(false)['errors'][0]['source']['pointer']);
}

public function testValidationErrorStatusFollowsTheResponseStatus(): void
{
$response = self::createClient()->request('POST', '/jsonapi_validation_problem_bad_request', [
'headers' => ['accept' => 'application/vnd.api+json', 'content-type' => 'application/vnd.api+json'],
'json' => ['data' => ['type' => 'JsonApiErrorProblem', 'attributes' => new \stdClass()]],
]);

$this->assertResponseStatusCodeSame(400);
$this->assertSame('400', $response->toArray(false)['errors'][0]['status'] ?? null);
}
}
4 changes: 3 additions & 1 deletion tests/Functional/JsonApi/ErrorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ public function testValidationErrorRendersJsonApiPointer(): void
$this->assertJsonEquals([
'errors' => [
[
'status' => '422',
'title' => 'Validation Failed',
'detail' => 'This value should not be blank.',
'source' => ['pointer' => 'data/attributes/name'],
'source' => ['pointer' => '/data/attributes/name'],
],
],
]);
Expand Down
Loading