Skip to content

Commit

Permalink
ArrayPropertyMappingPopulator: support null as source array prope…
Browse files Browse the repository at this point in the history
…rty value (#67)

Co-authored-by: Jacob Dreesen <j.dreesen@neusta.de>
  • Loading branch information
mike4git and jdreesen authored Mar 15, 2024
1 parent b7451e9 commit 7873b53
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
17 changes: 11 additions & 6 deletions src/Populator/ArrayPropertyMappingPopulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions tests/Fixtures/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ class User
/** @var array<string> */
private array $favouriteMovies;

/** @var array<Hobby> */
private array $hobbies;
/** @var array<Hobby>|null */
private ?array $hobbies;

/** @var array<Phone> */
private array $phones;
Expand Down Expand Up @@ -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;

Expand Down
11 changes: 11 additions & 0 deletions tests/Populator/ArrayPropertyMappingPopulatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

0 comments on commit 7873b53

Please sign in to comment.