Skip to content

Commit

Permalink
Fix: Honor default value
Browse files Browse the repository at this point in the history
  • Loading branch information
antoninmasek committed Aug 15, 2023
1 parent dac7434 commit a7e5a1d
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ public static function hydrate(string $className, array $data = null): ?object
$publicProperties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC);

foreach ($publicProperties as $property) {
$value = array_key_exists($property->getName(), $data)
? $data[$property->getName()]
: null;
$value = ! array_key_exists($property->getName(), $data)
? $property->getDefaultValue()
: $data[$property->getName()];

$property->setValue(
$dto,
Expand Down
2 changes: 2 additions & 0 deletions tests/Models/Car.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class Car

public ?Color $color;

public ?int $maxSpeed = 120;

public ?ClassThatNeedsCustomCaster $customCaster;

#[Collection(Key::class)]
Expand Down
44 changes: 44 additions & 0 deletions tests/SimpleHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -432,4 +432,48 @@ public function testEnumCanBeNull()

$this->assertNull($camaro->color);
}

public function testItHonorsDefaultValue()
{
$data = [
'brand' => 'Chevrolet',
'type' => 'Camaro',
'keys' => null,
];

/** @var Car $camaro */
$camaro = Hydrator::hydrate(Car::class, $data);

$this->assertSame(120, $camaro->maxSpeed);
}

public function testItCanOverwritesDefaultValue()
{
$data = [
'brand' => 'Chevrolet',
'type' => 'Camaro',
'maxSpeed' => 250,
'keys' => null,
];

/** @var Car $camaro */
$camaro = Hydrator::hydrate(Car::class, $data);

$this->assertSame(250, $camaro->maxSpeed);
}

public function testItCanOverwritesDefaultValueWithNull()
{
$data = [
'brand' => 'Chevrolet',
'type' => 'Camaro',
'maxSpeed' => null,
'keys' => null,
];

/** @var Car $camaro */
$camaro = Hydrator::hydrate(Car::class, $data);

$this->assertNull($camaro->maxSpeed);
}
}

0 comments on commit a7e5a1d

Please sign in to comment.