Skip to content

fix(serializer): Allow nested denormalization when allow_extra_attributes=false #7270

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

Open
wants to merge 6 commits into
base: 4.1
Choose a base branch
from
Open
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
21 changes: 21 additions & 0 deletions src/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@
}
}

// See https://github.com/api-platform/core/pull/7270 - id may be an allowed attribute due to being added in the
// overridden getAllowedAttributes below, in order to allow updating a nested item via ID. But in this case it
// may not "really" be an allowed attribute, ie we don't want to actually use it in denormalization. In this
// scenario it will not be present in parent::getAllowedAttributes
if (isset($data['id'], $context['resource_class'])) {
$parentAllowedAttributes = parent::getAllowedAttributes($class, $context, true);
if (\is_array($parentAllowedAttributes) && !\in_array('id', $parentAllowedAttributes, true)) {
unset($data['id']);

Check warning on line 78 in src/Serializer/ItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/ItemNormalizer.php#L75-L78

Added lines #L75 - L78 were not covered by tests
}
}

return parent::denormalize($data, $class, $format, $context);
}

Expand Down Expand Up @@ -107,4 +118,14 @@

return $uriVariables;
}

protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool

Check warning on line 122 in src/Serializer/ItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/ItemNormalizer.php#L122

Added line #L122 was not covered by tests
{
$allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
$allowedAttributes = array_merge($allowedAttributes, ['id']);

Check warning on line 126 in src/Serializer/ItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/ItemNormalizer.php#L124-L126

Added lines #L124 - L126 were not covered by tests
Copy link
Member

Choose a reason for hiding this comment

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

what if id isn't the property/attribute used to identify a resource?

Copy link
Author

Choose a reason for hiding this comment

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

Hello, possibly I'm misunderstanding what you mean, I think it always will be id, as it's not configurable is it? And it's also hardcoded eg here:

private function updateObjectToPopulate(array $data, array &$context): void
{
    try {
        $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri((string) $data['id'], $context + ['fetch_data' => true]);

When/how could it be something else?

}

return $allowedAttributes;

Check warning on line 129 in src/Serializer/ItemNormalizer.php

View check run for this annotation

Codecov / codecov/patch

src/Serializer/ItemNormalizer.php#L129

Added line #L129 was not covered by tests
}
}
71 changes: 71 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Issue6225/Bar6225.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Entity\Issue6225;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity]
#[ORM\Table(name: 'bar6225')]
#[ApiResource]
class Bar6225
{
public function __construct()
{
$this->id = Uuid::v7();
}

#[ORM\Id]
#[ORM\Column(type: 'symfony_uuid', unique: true)]
#[Groups(['Foo:Read'])]
private Uuid $id;

#[ORM\OneToOne(mappedBy: 'bar', cascade: ['persist', 'remove'])]
private ?Foo6225 $foo;

#[ORM\Column(length: 255)]
#[Groups(['Foo:Write', 'Foo:Read'])]
private string $someProperty;

public function getId(): Uuid
{
return $this->id;
}

public function getFoo(): Foo6225
{
return $this->foo;
}

public function setFoo(Foo6225 $foo): static
{
$this->foo = $foo;

return $this;
}

public function getSomeProperty(): string
{
return $this->someProperty;
}

public function setSomeProperty(string $someProperty): static
{
$this->someProperty = $someProperty;

return $this;
}
}
71 changes: 71 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Issue6225/Foo6225.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Entity\Issue6225;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity()]
#[ORM\Table(name: 'foo6225')]
#[ApiResource(
operations: [
new Post(),
new Patch(),
],
normalizationContext: [
'groups' => ['Foo:Read'],
],
denormalizationContext: [
'allow_extra_attributes' => false,
'groups' => ['Foo:Write'],
],
)]
class Foo6225
{
public function __construct()
{
$this->id = Uuid::v7();
}

#[ORM\Id]
#[ORM\Column(type: 'symfony_uuid', unique: true)]
#[Groups(['Foo:Read'])]
private Uuid $id;

#[ORM\OneToOne(inversedBy: 'foo', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['Foo:Write', 'Foo:Read'])]
private Bar6225 $bar;

public function getId(): Uuid
{
return $this->id;
}

public function getBar(): Bar6225
{
return $this->bar;
}

public function setBar(Bar6225 $bar): static
{
$this->bar = $bar;

return $this;
}
}
78 changes: 78 additions & 0 deletions tests/Functional/NestedPatchTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Functional;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue6225\Bar6225;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue6225\Foo6225;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;

class NestedPatchTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

public static function getResources(): array
{
return [Foo6225::class, Bar6225::class];
}

public function testIssue6225(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped();
}

$this->recreateSchema(self::getResources());

$response = self::createClient()->request('POST', '/foo6225s', [
'json' => [
'bar' => [
'someProperty' => 'abc',
],
],
'headers' => [
'accept' => 'application/json',
],
]);
static::assertResponseIsSuccessful();
$responseContent = json_decode($response->getContent(), true);
$createdFooId = $responseContent['id'];
$createdBarId = $responseContent['bar']['id'];

$patchResponse = self::createClient()->request('PATCH', '/foo6225s/'.$createdFooId, [
'json' => [
'bar' => [
'id' => $createdBarId,
'someProperty' => 'def',
],
],
'headers' => [
'accept' => 'application/json',
'content-type' => 'application/merge-patch+json',
],
]);
static::assertResponseIsSuccessful();
static::assertEquals([
'id' => $createdFooId,
'bar' => [
'id' => $createdBarId,
'someProperty' => 'def',
],
], json_decode($patchResponse->getContent(), true));
}
}
Loading