Skip to content

Commit

Permalink
fix(symfony): set normalization context in request attributes (#6345)
Browse files Browse the repository at this point in the history
  • Loading branch information
soyuka committed May 2, 2024
1 parent f63fd81 commit 735e150
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/State/Provider/ReadProvider.php
Expand Up @@ -71,10 +71,11 @@ public function provide(Operation $operation, array $uriVariables = [], array $c

if ($this->serializerContextBuilder && $request) {
// Builtin data providers are able to use the serialization context to automatically add join clauses
$context += $this->serializerContextBuilder->createFromRequest($request, true, [
$context += $normalizationContext = $this->serializerContextBuilder->createFromRequest($request, true, [
'resource_class' => $operation->getClass(),
'operation' => $operation,
]);
$request->attributes->set('_api_normalization_context', $normalizationContext);
}

try {
Expand Down
38 changes: 38 additions & 0 deletions src/State/Tests/Provider/ReadProviderTest.php
@@ -0,0 +1,38 @@
<?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\State\Tests\Provider;

use ApiPlatform\Metadata\Get;
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\State\Provider\ReadProvider;
use ApiPlatform\State\ProviderInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

class ReadProviderTest extends TestCase
{
public function testSetsSerializerContext(): void
{
$data = new \stdClass();
$operation = new Get(read: true);
$decorated = $this->createStub(ProviderInterface::class);
$decorated->method('provide')->willReturn($data);
$serializerContextBuilder = $this->createMock(SerializerContextBuilderInterface::class);
$serializerContextBuilder->expects($this->once())->method('createFromRequest')->willReturn(['a']);
$provider = new ReadProvider($decorated, $serializerContextBuilder);
$request = new Request();
$provider->provide($operation, ['id' => 1], ['request' => $request]);
$this->assertEquals(['a'], $request->attributes->get('_api_normalization_context'));
}
}
3 changes: 2 additions & 1 deletion src/State/composer.json
Expand Up @@ -36,7 +36,8 @@
"symfony/web-link": "^6.4 || ^7.0",
"symfony/http-foundation": "^6.4 || 7.0",
"willdurand/negotiation": "^3.1",
"api-platform/validator": "*@dev || ^3.1"
"api-platform/validator": "*@dev || ^3.1",
"api-platform/serializer": "*@dev || ^3.1"
},
"autoload": {
"psr-4": {
Expand Down

0 comments on commit 735e150

Please sign in to comment.