Skip to content

Commit

Permalink
Fix: Already existing enum
Browse files Browse the repository at this point in the history
  • Loading branch information
antoninmasek committed Aug 15, 2023
1 parent 7652b8c commit dac7434
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/Casters/EnumCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public function cast(mixed $value): mixed
return null;
}

if ($value instanceof $this->class_name) {
return $value;
}

return $this->class_name::from($value);
}
}
17 changes: 16 additions & 1 deletion tests/SimpleHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ public function testItThrowsExceptionWhenAssociativeArrayIsUsedWithCollectionFro
Human::collectionFromArray($this->data);
}

public function testItCanParseEnum()
public function testItCanParseEnumFromValue()
{
$data = [
'brand' => 'Chevrolet',
Expand All @@ -388,6 +388,21 @@ public function testItCanParseEnum()
$this->assertSame(Color::YELLOW, $camaro->color);
}

public function testItCanParseEnum()
{
$data = [
'brand' => 'Chevrolet',
'color' => Color::YELLOW,
'type' => 'Camaro',
'keys' => null,
];

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

$this->assertSame(Color::YELLOW, $camaro->color);
}

public function testItFailsWithInvalidEnum()
{
$data = [
Expand Down

0 comments on commit dac7434

Please sign in to comment.