Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(serializer): use data if no uri_variables provided #5743

Merged
merged 1 commit into from
Aug 11, 2023
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
22 changes: 22 additions & 0 deletions features/main/patch.feature
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,25 @@ Feature: Sending PATCH requets
}
}
"""

Scenario: Patch a relation with uri variables that are not `id`
When I add "Content-Type" header equal to "application/merge-patch+json"
And I send a "PATCH" request to "/betas/1" with body:
"""
{
"alpha": "/alphas/2"
}
"""
Then the response should be in JSON
And the response status code should be 200
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
And the JSON should be equal to:
"""
{
"@context": "/contexts/Beta",
"@id": "/betas/1",
"@type": "Beta",
"betaId": 1,
"alpha": "/alphas/2"
}
"""
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Aerendir this works right now so I'm not sure what the issue is, are you using merge-patch?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@soyuka , no, I'm using PUTs... I'm going to reproduce the scenario...

53 changes: 31 additions & 22 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use ApiPlatform\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
Expand Down Expand Up @@ -512,12 +513,7 @@

$collectionKeyType = $type->getCollectionKeyTypes()[0] ?? null;
$collectionKeyBuiltinType = $collectionKeyType?->getBuiltinType();
$childContext = $this->createChildContext(['resource_class' => $className] + $context, $attribute, $format);
unset($childContext['uri_variables']);
if ($this->resourceMetadataCollectionFactory) {
$childContext['operation'] = $this->resourceMetadataCollectionFactory->create($className)->getOperation();
}

$childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
$values = [];
foreach ($value as $index => $obj) {
if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
Expand Down Expand Up @@ -637,8 +633,7 @@
}

$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
$childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);

return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
}
Expand All @@ -653,12 +648,7 @@
}

$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
$childContext['resource_class'] = $resourceClass;
if ($this->resourceMetadataCollectionFactory) {
$childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
}
unset($childContext['iri'], $childContext['uri_variables']);
$childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);

return $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
}
Expand All @@ -670,17 +660,16 @@
unset($context['resource_class']);
unset($context['force_resource_class']);

// Anonymous resources
if ($type && $type->getClassName()) {
$childContext = $this->createChildContext($context, $attribute, $format);
unset($childContext['iri'], $childContext['uri_variables']);
$childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;

return $this->serializer->normalize($attributeValue, $format, $childContext);
}

if ($type && 'array' === $type->getBuiltinType()) {
$childContext = $this->createChildContext($context, $attribute, $format);
unset($childContext['iri'], $childContext['uri_variables']);

return $this->serializer->normalize($attributeValue, $format, $childContext);
}
Expand Down Expand Up @@ -804,12 +793,7 @@
&& $this->resourceClassResolver->isResourceClass($className)
) {
$resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
$childContext['resource_class'] = $resourceClass;
unset($childContext['uri_variables']);
if ($this->resourceMetadataCollectionFactory) {
$childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
}
$childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);

return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
}
Expand Down Expand Up @@ -899,4 +883,29 @@
// Properties not found are ignored
}
}

private function createOperationContext(array $context, string $resourceClass = null): array
{
if (isset($context['operation']) && !isset($context['root_operation'])) {
$context['root_operation'] = $context['operation'];
$context['root_operation_name'] = $context['operation_name'];
}

unset($context['iri'], $context['uri_variables']);
if (!$resourceClass) {
return $context;

Check warning on line 896 in src/Serializer/AbstractItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/AbstractItemNormalizer.php#L896

Added line #L896 was not covered by tests
}

unset($context['operation'], $context['operation_name']);
$context['resource_class'] = $resourceClass;
if ($this->resourceMetadataCollectionFactory) {
try {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
$context['operation_name'] = $context['operation']->getName();
} catch (OperationNotFoundException) {

Check warning on line 905 in src/Serializer/AbstractItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/AbstractItemNormalizer.php#L905

Added line #L905 was not covered by tests
}
}

return $context;
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonag can you try this and use root_operation?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updating to API Platform v3.1.14 and changing my custom normalizer to use the root_operation instead of the operation fixes all my tests!
Thank you 👏!

}
6 changes: 1 addition & 5 deletions src/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,7 @@ private function updateObjectToPopulate(array $data, array &$context): void

private function getContextUriVariables(array $data, $operation, array $context): array
{
if (!isset($context['uri_variables'])) {
return ['id' => $data['id']];
}

$uriVariables = $context['uri_variables'];
$uriVariables = $context['uri_variables'] ?? $data;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Aerendir can you try this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @soyuka , I've tried the fix, but it doesn't work...

In ItemNormalizer::getContextUriVariables(), there is no key $context['uri_variables'], so the variable $uriVariable gets the value of $data, but $data contains the entity and so there will never be the uri variables needed.

I'm going to reproduce in tests what's going on...


/** @var Link $uriVariable */
foreach ($operation->getUriVariables() as $uriVariable) {
Expand Down
33 changes: 33 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/Issue5736/Alpha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?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\Fixtures\TestBundle\ApiResource\Issue5736;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Operation;

#[Get(
provider: [Alpha::class, 'provide'],
)]
final class Alpha
{
public function __construct(#[ApiProperty(identifier: true)] public int $alphaId)
{
}

public static function provide(Operation $operation, array $uriVariables = []): self
{
return new self(alphaId: $uriVariables['alphaId']);
}
}
39 changes: 39 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/Issue5736/Beta.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?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\Fixtures\TestBundle\ApiResource\Issue5736;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;

#[Patch(
processor: [Beta::class, 'process'],
provider: [Beta::class, 'provide'],
)]
final class Beta
{
public function __construct(#[ApiProperty(identifier: true)] public int $betaId, public ?Alpha $alpha = null)
{
}

public static function provide(Operation $operation, array $uriVariables = []): self
{
return new self(betaId: $uriVariables['betaId']);
}

public static function process($body)
{
return $body;
}
}
Loading