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

Fixing Bug #249 #251

Merged
merged 8 commits into from
Jun 2, 2022
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
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);
}
}