Skip to content
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
14 changes: 12 additions & 2 deletions src/IsMigrationDataTransferObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use ReflectionClass;
use ReflectionParameter;
use ReflectionProperty;
use Webmozart\Assert\Assert;

Expand Down Expand Up @@ -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;
}

Expand All @@ -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);
Expand Down
17 changes: 17 additions & 0 deletions tests/MigrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down