Skip to content
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
62 changes: 62 additions & 0 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement
public const SKIP_NULL_TO_ONE_RELATIONS = 'skip_null_to_one_relations';
private const TYPE_PROPERTY_FORMAT = 'api_type_property_format';

public const MERGE_PATCH_MAPS = 'api_merge_patch_maps';

protected PropertyAccessorInterface $propertyAccessor;
protected array $localCache = [];
protected array $localFactoryOptionsCache = [];
Expand Down Expand Up @@ -891,6 +893,23 @@ protected function setAttributeValue(object $object, string $attribute, mixed $v
return;
}

if (\is_array($value)
&& ($context[self::MERGE_PATCH_MAPS] ?? $this->defaultContext[self::MERGE_PATCH_MAPS] ?? false)
&& ($context['api_allow_update'] ?? false)
&& ($context[static::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[static::DEEP_OBJECT_TO_POPULATE] ?? false)
&& null !== $mapType = $this->getStringKeyedMapType($this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context))->getNativeType())
) {
try {
$currentValue = $this->propertyAccessor->getValue($object, $attribute);
} catch (NoSuchPropertyException|UninitializedPropertyException) {
$currentValue = null;
}

if (\is_array($currentValue)) {
$value = $this->mergePatchMap($currentValue, $value, $mapType->getCollectionValueType());
}
}

// symfony/serializer only reads the current value of typed attributes (https://github.com/symfony/symfony/pull/67883), and it can't type them here
if (!isset($context[static::OBJECT_TO_POPULATE])
&& ($context[static::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[static::DEEP_OBJECT_TO_POPULATE] ?? false)
Expand All @@ -914,6 +933,49 @@ protected function setAttributeValue(object $object, string $attribute, mixed $v
}
}

private function getStringKeyedMapType(?Type $type): ?CollectionType
{
if ($type instanceof NullableType) {
$type = $type->getWrappedType();
}

if (!$type instanceof CollectionType || $type->isList()) {
return null;
}

$keyType = $type->getCollectionKeyType();

return $keyType instanceof BuiltinType && TypeIdentifier::STRING === $keyType->getTypeIdentifier() ? $type : null;
}

private function mergePatchMap(array $target, array $patch, Type $valueType): array
{
$nestedMapType = $this->getStringKeyedMapType($valueType);
$isUntypedValue = $valueType instanceof BuiltinType && TypeIdentifier::MIXED === $valueType->getTypeIdentifier();

foreach ($patch as $key => $patchValue) {
if (null === $patchValue) {
unset($target[$key]);
continue;
}

if (\is_array($patchValue) && $nestedMapType) {
$target[$key] = $this->mergePatchMap(\is_array($target[$key] ?? null) ? $target[$key] : [], $patchValue, $nestedMapType->getCollectionValueType());
continue;
}

if (\is_array($patchValue) && $isUntypedValue && !array_is_list($patchValue)) {
$currentValue = $target[$key] ?? null;
$target[$key] = $this->mergePatchMap(\is_array($currentValue) && !array_is_list($currentValue) ? $currentValue : [], $patchValue, $valueType);
continue;
}

$target[$key] = $patchValue;
}

return $target;
}

/**
* Validates the type of the value. Allows using integers as floats for JSON formats.
*
Expand Down
1 change: 1 addition & 0 deletions src/State/SerializerContextBuilderInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ interface SerializerContextBuilderInterface
* force_resource_class?: class-string,
* api_allow_update?: bool,
* deep_object_to_populate?: bool,
* api_merge_patch_maps?: bool,
* collect_denormalization_errors?: bool,
* exclude_from_cache_key?: string[],
* api_included?: bool,
Expand Down
56 changes: 56 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/Settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?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;

use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use Symfony\Component\Validator\Constraints as Assert;

#[Get(uriTemplate: '/merge_patch_settings/{id}', provider: [self::class, 'provide'])]
#[Patch(
uriTemplate: '/merge_patch_settings/{id}',
denormalizationContext: ['api_merge_patch_maps' => true],
provider: [self::class, 'provide'],
processor: [self::class, 'process'],
)]
#[Patch(
uriTemplate: '/merge_patch_settings/{id}/replace',
provider: [self::class, 'provide'],
processor: [self::class, 'process'],
)]
class Settings
{
public int $id;

/**
* @var array<string, mixed>
*/
#[Assert\Count(max: 3)]
public array $settings = [];

public static function provide(Operation $operation, array $uriVariables = []): self
{
$settings = new self();
$settings->id = (int) $uriVariables['id'];
$settings->settings = ['a' => 1, 'b' => 2, 'c' => ['e' => 2]];

return $settings;
}

public static function process(mixed $data): mixed
{
return $data;
}
}
63 changes: 63 additions & 0 deletions tests/Functional/Serializer/MergePatchMapsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?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\Functional\Serializer;

use ApiPlatform\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Settings;
use ApiPlatform\Tests\SetupClassResourcesTrait;

final class MergePatchMapsTest extends ApiTestCase
{
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

public static function getResources(): array
{
return [Settings::class];
}

public function testMergePatchMergesMapWhenOptedIn(): void
{
$response = self::createClient()->request('PATCH', '/merge_patch_settings/1', [
'headers' => ['Content-Type' => 'application/merge-patch+json'],
'json' => ['settings' => ['b' => null, 'c' => ['d' => 1]]],
]);

$this->assertResponseStatusCodeSame(200);
$this->assertSame(['a' => 1, 'c' => ['e' => 2, 'd' => 1]], $response->toArray()['settings']);
}

public function testMergePatchValidatesMergedMap(): void
{
self::createClient()->request('PATCH', '/merge_patch_settings/1', [
'headers' => ['Content-Type' => 'application/merge-patch+json'],
'json' => ['settings' => ['x' => 1]],
]);

$this->assertResponseStatusCodeSame(422);
$this->assertJsonContains(['violations' => [['propertyPath' => 'settings']]]);
}

public function testMergePatchReplacesMapWithoutOptIn(): void
{
$response = self::createClient()->request('PATCH', '/merge_patch_settings/1/replace', [
'headers' => ['Content-Type' => 'application/merge-patch+json'],
'json' => ['settings' => ['b' => null, 'c' => ['d' => 1]]],
]);

$this->assertResponseStatusCodeSame(200);
$this->assertSame(['b' => null, 'c' => ['d' => 1]], $response->toArray()['settings']);
}
}
Loading