diff --git a/src/DataTransferObject.php b/src/DataTransferObject.php index d1ecefff..2b2d7198 100644 --- a/src/DataTransferObject.php +++ b/src/DataTransferObject.php @@ -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); } diff --git a/src/Reflection/DataTransferObjectProperty.php b/src/Reflection/DataTransferObjectProperty.php index abdf313d..843bd8d4 100644 --- a/src/Reflection/DataTransferObjectProperty.php +++ b/src/Reflection/DataTransferObjectProperty.php @@ -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); diff --git a/tests/MapFromTest.php b/tests/MapFromTest.php index eac70a43..240cd8eb 100644 --- a/tests/MapFromTest.php +++ b/tests/MapFromTest.php @@ -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); + } }