Skip to content

Commit

Permalink
Fix: Hydrate boolean values using filter_var
Browse files Browse the repository at this point in the history
  • Loading branch information
antoninmasek committed Aug 30, 2023
1 parent a7e5a1d commit fc64d95
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ private static function hydrateProperty(\ReflectionProperty $property, mixed $va
}

if ($property->getType()->isBuiltin()) {
return $value;
return match ($property->getType()->getName()) {
'bool' => filter_var($value, FILTER_VALIDATE_BOOL),
default => $value,
};
}

return self::cast($property->getType()->getName(), $value, $allowsNull);
Expand Down
25 changes: 25 additions & 0 deletions tests/SimpleHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,31 @@ public function testItCanHydrateObjectUsingHydrator()
$this->assertSame('Porsche', $car->brand);
}

public function testItCanHydrateBool()
{
$data = $this->data;
$data['male'] = false;

$person = Hydrator::hydrate(Human::class, $data);
$this->assertSame(false, $person->male);

$data['male'] = 'true';
$person = Hydrator::hydrate(Human::class, $data);
$this->assertSame(true, $person->male);

$data['male'] = 'false';
$person = Hydrator::hydrate(Human::class, $data);
$this->assertSame(false, $person->male);

$data['male'] = 'TRUE';
$person = Hydrator::hydrate(Human::class, $data);
$this->assertSame(true, $person->male);

$data['male'] = 'FALSE';
$person = Hydrator::hydrate(Human::class, $data);
$this->assertSame(false, $person->male);
}

public function testObjectCanHydrateItselfWhenExtendingHydrator()
{
$person = Human::fromArray($this->data);
Expand Down

0 comments on commit fc64d95

Please sign in to comment.