Skip to content

Commit

Permalink
fix(laravel): jsonapi error serialization (#6755)
Browse files Browse the repository at this point in the history
  • Loading branch information
soyuka authored Oct 25, 2024
1 parent 8bb3d39 commit 609f8c2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
29 changes: 27 additions & 2 deletions Serializer/ErrorNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,34 @@ public function normalize(mixed $object, ?string $format = null, array $context
$jsonApiObject = $this->itemNormalizer->normalize($object, $format, $context);
$error = $jsonApiObject['data']['attributes'];
$error['id'] = $jsonApiObject['data']['id'];
$error['type'] = $jsonApiObject['data']['id'];
if (isset($error['type'])) {
$error['links'] = ['type' => $error['type']];
}

if (!isset($error['code']) && method_exists($object, 'getId')) {
$error['code'] = $object->getId();
}

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' => [$error]];
return ['errors' => $errors];
}

/**
Expand Down
5 changes: 5 additions & 0 deletions Serializer/ReservedAttributeNameConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\JsonApi\Serializer;

use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

Expand Down Expand Up @@ -44,6 +45,10 @@ public function normalize(string $propertyName, ?string $class = null, ?string $
$propertyName = $this->nameConverter->normalize($propertyName, $class, $format, $context);
}

if ($class && is_a($class, ProblemExceptionInterface::class, true)) {
return $propertyName;
}

if (isset(self::JSON_API_RESERVED_ATTRIBUTES[$propertyName])) {
$propertyName = self::JSON_API_RESERVED_ATTRIBUTES[$propertyName];
}
Expand Down

0 comments on commit 609f8c2

Please sign in to comment.