Skip to content

Commit 8af532f

Browse files
committed
fix(jsonld): prefix error @type with hydra:
1 parent a11c213 commit 8af532f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/JsonLd/Serializer/ErrorNormalizer.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,17 @@ public function __construct(private readonly NormalizerInterface $inner, private
2828

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

38+
if ('Error' === $normalized['@type']) {
39+
$normalized['@type'] = 'hydra:Error';
40+
}
41+
3742
if (isset($normalized['description'])) {
3843
$normalized['hydra:description'] = $normalized['description'];
3944
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace ApiPlatform\Tests\JsonLd\Serializer;
4+
5+
use ApiPlatform\JsonLd\ContextBuilder;
6+
use ApiPlatform\JsonLd\Serializer\ErrorNormalizer;
7+
use PHPUnit\Framework\TestCase;
8+
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
9+
10+
final class ErrorNormalizerTest extends TestCase
11+
{
12+
public function testAddHydraPrefix()
13+
{
14+
$provider = $this->createMock(NormalizerInterface::class);
15+
$provider->method('normalize')->willReturn(['@type' => 'Error', 'title' => 'foo', 'description' => 'bar']);
16+
$errorNormalizer = new ErrorNormalizer($provider, ['hydra_prefix' => ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX]);
17+
$res = $errorNormalizer->normalize(new \stdClass());
18+
$this->assertEquals('hydra:Error', $res['@type']);
19+
$this->assertArrayHasKey('hydra:description', $res);
20+
$this->assertEquals($res['hydra:description'], $res['description']);
21+
$this->assertArrayHasKey('hydra:title', $res);
22+
$this->assertEquals($res['hydra:title'], $res['title']);
23+
}
24+
}

0 commit comments

Comments
 (0)