diff --git a/src/IsMigrationDataTransferObject.php b/src/IsMigrationDataTransferObject.php index f92920b..dcda307 100644 --- a/src/IsMigrationDataTransferObject.php +++ b/src/IsMigrationDataTransferObject.php @@ -7,6 +7,7 @@ use Illuminate\Support\Str; use Illuminate\Support\Traits\ForwardsCalls; use ReflectionClass; +use ReflectionParameter; use ReflectionProperty; use Webmozart\Assert\Assert; @@ -88,8 +89,15 @@ public function fill(array $data) */ public function fillOrDefaults(array $data) { + $constructorParams = (new ReflectionClass(static::class))->getConstructor()?->getParameters() ?? []; + foreach ((new ReflectionClass(static::class))->getProperties() as $property) { - if (!$property->hasDefaultValue()) { + /** @var ReflectionParameter|null $promoted */ + $promoted = $property->isPromoted() ? + Arr::first($constructorParams, fn (ReflectionParameter $parameter) => $parameter->name === $property->name) : + null; + + if (!$property->hasDefaultValue() && !$promoted?->isDefaultValueAvailable()) { continue; } @@ -99,7 +107,9 @@ public function fillOrDefaults(array $data) continue; } - $property->setValue($property->getDefaultValue()); + $defaultValue = $promoted ? $promoted->getDefaultValue() : $property->getDefaultValue(); + + $property->setValue($this, $defaultValue); } return $this->fill($data); diff --git a/tests/MigrationTest.php b/tests/MigrationTest.php index a61e1d1..38f8caa 100644 --- a/tests/MigrationTest.php +++ b/tests/MigrationTest.php @@ -110,6 +110,23 @@ public function testLegacyConstruction(): void public function testLegacyConstructionFromArray(): void { + $dto = MigrationStubDTO::from([ + 'name' => 'test', + 'dto' => $stub = StubDTO::create()->setName('nested'), + 'enum' => TestEnum::$ONE, + ]); + + self::assertSame([ + 'name' => 'test', + 'dto' => $stub, + 'enum' => TestEnum::$ONE, + 'with_default' => null, + ], $dto->all()); + + self::assertNull($dto->withDefault); + self::assertNull($dto->getWithDefault()); + self::assertTrue($dto->hasWithDefault()); + $dto = MigrationStubDTO::from([ 'name' => 'test', 'dto' => $stub = StubDTO::create()->setName('nested'),