Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException as PropertyAccessInvalidArgumentException;
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
Expand Down Expand Up @@ -333,15 +334,16 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a

$nestedAttributes = $this->getNestedAttributes($mappedClass);
$nestedData = $originalNestedData = [];
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->enableExceptionOnInvalidIndex()->getPropertyAccessor();
foreach ($nestedAttributes as $property => $serializedPath) {
if (null === $value = $propertyAccessor->getValue($normalizedData, $serializedPath)) {
continue;
try {
$value = $propertyAccessor->getValue($normalizedData, $serializedPath);
$convertedProperty = $this->nameConverter ? $this->nameConverter->normalize($property, $mappedClass, $format, $context) : $property;
$nestedData[$convertedProperty] = $value;
$originalNestedData[$property] = $value;
$normalizedData = $this->removeNestedValue($serializedPath->getElements(), $normalizedData);
} catch (NoSuchIndexException) {
}
$convertedProperty = $this->nameConverter ? $this->nameConverter->normalize($property, $mappedClass, $format, $context) : $property;
$nestedData[$convertedProperty] = $value;
$originalNestedData[$property] = $value;
$normalizedData = $this->removeNestedValue($serializedPath->getElements(), $normalizedData);
}

$normalizedData = $nestedData + $normalizedData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,29 @@ public function testDenormalizeWithCorrectOrderOfAttributeAndProperty()
$this->assertSame('nested-id', $test->id);
}

public function testDenormalizeMissingAndNullNestedValues()
{
$normalizer = new AbstractObjectNormalizerWithMetadata();

$data = [
'data' => [
'foo' => null,
],
];

$obj = new class {
#[SerializedPath('[data][foo]')]
public ?string $foo;

#[SerializedPath('[data][bar]')]
public ?string $bar;
};

$test = $normalizer->denormalize($data, $obj::class);
$this->assertNull($test->foo);
$this->assertFalse((new \ReflectionProperty($obj, 'bar'))->isInitialized($obj));
}

public function testNormalizeBasedOnAllowedAttributes()
{
$normalizer = new class extends AbstractObjectNormalizer {
Expand Down
Loading