Skip to content
This repository has been archived by the owner on Nov 1, 2022. It is now read-only.

Commit

Permalink
Merge pull request #251 from gerpo/master
Browse files Browse the repository at this point in the history
Fixes #249
  • Loading branch information
aidan-casey authored Jun 2, 2022
2 parents 68296ba + 2387f6d commit 83c04ce
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/DataTransferObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function __construct(...$args)
$class = new DataTransferObjectClass($this);

foreach ($class->getProperties() as $property) {
$property->setValue(Arr::get($args, $property->name) ?? $this->{$property->name} ?? null);
$property->setValue(Arr::get($args, $property->name, $property->getDefaultValue()));

$args = Arr::forget($args, $property->name);
}
Expand Down
5 changes: 5 additions & 0 deletions src/Reflection/DataTransferObjectProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ public function getValue(): mixed
return $this->reflectionProperty->getValue($this->dataTransferObject);
}

public function getDefaultValue(): mixed
{
return $this->reflectionProperty->getDefaultValue();
}

private function resolveCaster(): ?Caster
{
$attributes = $this->reflectionProperty->getAttributes(CastWith::class);
Expand Down
26 changes: 26 additions & 0 deletions tests/MapFromTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,30 @@ public function dto_can_have_mapped_and_regular_properties()
$this->assertEquals('2021-01-01', $dto->date);
$this->assertEquals('News', $dto->categoryName);
}

/** @test */
public function mapped_from_works_with_default_values()
{
$data = [
'title' => 'Hello world',
];

$dto = new class ($data) extends DataTransferObject {
public string $title;

#[MapFrom('desc')]
public string $description = 'Test Text';

#[MapFrom('is_public')]
public bool $isPublic = false;

#[MapFrom('random_int')]
public int $randomInt = 42;
};

$this->assertEquals('Hello world', $dto->title);
$this->assertEquals('Test Text', $dto->description);
$this->assertFalse($dto->isPublic);
$this->assertEquals(42, $dto->randomInt);
}
}

0 comments on commit 83c04ce

Please sign in to comment.