diff --git a/src/Populator/ArrayPropertyMappingPopulator.php b/src/Populator/ArrayPropertyMappingPopulator.php index 6dbb072..7f4cc4a 100644 --- a/src/Populator/ArrayPropertyMappingPopulator.php +++ b/src/Populator/ArrayPropertyMappingPopulator.php @@ -45,12 +45,17 @@ public function __construct( public function populate(object $target, object $source, ?object $ctx = null): void { try { - $unwrappedArray = array_map( - fn ($item) => null !== $this->sourceArrayItemProperty - ? $this->arrayItemAccessor->getValue($item, $this->sourceArrayItemProperty) - : $item, - $this->accessor->getValue($source, $this->sourceArrayProperty), - ); + $sourceArrayPropertyValues = $this->accessor->getValue($source, $this->sourceArrayProperty); + + $unwrappedArray = []; + if (\is_array($sourceArrayPropertyValues) && [] !== $sourceArrayPropertyValues) { + $unwrappedArray = array_map( + fn ($item) => null !== $this->sourceArrayItemProperty + ? $this->arrayItemAccessor->getValue($item, $this->sourceArrayItemProperty) + : $item, + $sourceArrayPropertyValues, + ); + } $this->accessor->setValue( $target, diff --git a/tests/Fixtures/Model/User.php b/tests/Fixtures/Model/User.php index 3a8ed3e..0382c06 100644 --- a/tests/Fixtures/Model/User.php +++ b/tests/Fixtures/Model/User.php @@ -17,8 +17,8 @@ class User /** @var array */ private array $favouriteMovies; - /** @var array */ - private array $hobbies; + /** @var array|null */ + private ?array $hobbies; /** @var array */ private array $phones; @@ -119,12 +119,12 @@ public function setFavouriteMovies(array $favouriteMovies): self return $this; } - public function getHobbies(): array + public function getHobbies(): ?array { return $this->hobbies; } - public function setHobbies(array $hobbies): self + public function setHobbies(?array $hobbies): self { $this->hobbies = $hobbies; diff --git a/tests/Populator/ArrayPropertyMappingPopulatorTest.php b/tests/Populator/ArrayPropertyMappingPopulatorTest.php index a82a666..e5b6a1a 100644 --- a/tests/Populator/ArrayPropertyMappingPopulatorTest.php +++ b/tests/Populator/ArrayPropertyMappingPopulatorTest.php @@ -46,4 +46,15 @@ public function test_populateWithInnerProperty(): void self::assertEquals(['reading', 'swimming', 'computers'], $person->getActivities()); } + + public function test_populateWithInnerProperty_is_null(): void + { + $populator = new ArrayPropertyMappingPopulator('activities', 'hobbies', 'label'); + $user = (new User())->setHobbies(null); + $person = new Person(); + + $populator->populate($person, $user); + + self::assertEmpty($person->getActivities()); + } }