From 2443187bebd6c569b212df7a36cb76fdce21b5be Mon Sep 17 00:00:00 2001 From: Alan Poulain Date: Wed, 9 Jul 2025 09:36:52 +0200 Subject: [PATCH] feat(serializer): handle defaultType for DiscriminatorMap --- src/Serializer/AbstractItemNormalizer.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index ae8475058ee..cd1f08ddc49 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -399,11 +399,13 @@ protected function getClassDiscriminatorResolvedClass(array $data, string $class return $class; } - if (!isset($data[$mapping->getTypeProperty()])) { + // @phpstan-ignore-next-line function.alreadyNarrowedType + $defaultType = method_exists($mapping, 'getDefaultType') ? $mapping->getDefaultType() : null; + if (!isset($data[$mapping->getTypeProperty()]) && null === $defaultType) { throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Type property "%s" not found for the abstract object "%s".', $mapping->getTypeProperty(), $class), null, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty()); } - $type = $data[$mapping->getTypeProperty()]; + $type = $data[$mapping->getTypeProperty()] ?? $defaultType; if (null === ($mappedClass = $mapping->getClassForType($type))) { throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" is not a valid value.', $type), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), true); }