Skip to content

Commit

Permalink
fix(jsonld): prefix error @type with hydra:
Browse files Browse the repository at this point in the history
  • Loading branch information
soyuka committed Oct 14, 2024
1 parent a11c213 commit b611059
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/JsonLd/Serializer/ErrorNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,17 @@ public function __construct(private readonly NormalizerInterface $inner, private

public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$context = $context + $this->defaultContext;
$normalized = $this->inner->normalize($object, $format, $context);
$hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
$hydraPrefix = $this->getHydraPrefix($context);
if (!$hydraPrefix) {
return $normalized;
}

if ('Error' === $normalized['@type']) {
$normalized['@type'] = 'hydra:Error';
}

if (isset($normalized['description'])) {
$normalized['hydra:description'] = $normalized['description'];
}
Expand Down
22 changes: 22 additions & 0 deletions tests/JsonLd/Serializer/ErrorNormalizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace ApiPlatform\Tests\JsonLd\Serializer;

use ApiPlatform\JsonLd\ContextBuilder;
use ApiPlatform\JsonLd\Serializer\ErrorNormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class ErrorNormalizerTest extends TestCase
{
public function testAddHydraPrefix()
{
$provider = $this->createMock(NormalizerInterface::class);
$provider->method('normalize')->willReturn(['@type' => 'Error', 'title' => 'foo', 'description' => 'bar']);
$errorNormalizer = new ErrorNormalizer($provider, ['hydra_prefix' => ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX]);
$res = $errorNormalizer->normalize(new \stdClass());
$this->assertEquals('hydra:Error', $res['@type']);
$this->assertEquals('hydra:description', $res['description']);
$this->assertEquals('hydra:title', $res['title']);
}
}

0 comments on commit b611059

Please sign in to comment.