Skip to content

Commit

Permalink
fix: compare enum with strict
Browse files Browse the repository at this point in the history
  • Loading branch information
ducconit committed Aug 7, 2024
1 parent 10b91c7 commit e7c443d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
5 changes: 2 additions & 3 deletions src/EnumComparable.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ trait EnumComparable
{
public function is(mixed $value, bool $strict = true): bool
{
$selfValue = self::getValue($this);
$targetValue = self::getValue($value);
$selfValue = self::getValue($this, strict: $strict);
$targetValue = self::getValue($value, strict: $strict);
if (is_null($selfValue) || is_null($targetValue)) {
var_dump([$targetValue,$value]);
return false;
}

Expand Down
14 changes: 10 additions & 4 deletions src/EnumValueResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ protected static function throwOrNull(mixed $name, bool $throw = true): null
/**
* @throws Throwable
*/
public static function getValue(int|string|self $name, bool $throw = false): int|string|null
public static function getValue(int|string|self|null $name, bool $strict = true, bool $throw = false): int|string|null
{
if (is_null($name)) {
return null;
}
if ($name instanceof UnitEnum) {
return static::getValueFromInstance($name);
}
if (is_int($name)) {
return static::tryFrom($name) ?? self::throwOrNull($name, $throw);
return static::getValue(static::tryFrom($name) ?? self::throwOrNull($name, $throw));
}

$enum = static::tryFromName($name);
Expand All @@ -53,10 +56,13 @@ public static function getValue(int|string|self $name, bool $throw = false): int
if (! is_numeric($name)) {
return self::throwOrNull($name, $throw);
}
return static::tryFrom((int) $name)?->value;
if ($strict && !is_int($name)) {
return self::throwOrNull($name, $throw);
}
return static::getValue(static::tryFrom((int)$name) ?? self::throwOrNull($name, $throw));
}
if ($backingType?->getName() === 'string') {
return static::tryFrom($name)?->value;
return static::getValue(static::tryFrom($name) ?? self::throwOrNull($name, $throw));
}
}
if (! $enum) {
Expand Down
1 change: 1 addition & 0 deletions tests/EnumCompareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
$status = EnumInt::ACTIVE;

expect($status->is('1'))->toBeFalse()
->and($status->is('1', false))->toBeTrue()
->and($status->is(1))->toBeTrue()
->and($status->is(EnumInt::ACTIVE))->toBeTrue();
});
Expand Down

0 comments on commit e7c443d

Please sign in to comment.