diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index 85e4e0959a6..e6732c21b72 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -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 = []; @@ -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) @@ -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. * diff --git a/src/State/SerializerContextBuilderInterface.php b/src/State/SerializerContextBuilderInterface.php index ef70685347a..93c5bfd1b81 100644 --- a/src/State/SerializerContextBuilderInterface.php +++ b/src/State/SerializerContextBuilderInterface.php @@ -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, diff --git a/tests/Fixtures/TestBundle/ApiResource/Settings.php b/tests/Fixtures/TestBundle/ApiResource/Settings.php new file mode 100644 index 00000000000..c829e127a9e --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/Settings.php @@ -0,0 +1,56 @@ + + * + * 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 + */ + #[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; + } +} diff --git a/tests/Functional/Serializer/MergePatchMapsTest.php b/tests/Functional/Serializer/MergePatchMapsTest.php new file mode 100644 index 00000000000..e32878d16f5 --- /dev/null +++ b/tests/Functional/Serializer/MergePatchMapsTest.php @@ -0,0 +1,63 @@ + + * + * 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']); + } +}