From e7c443d388d402fe346f8b1e715f0ddc0cd634fe Mon Sep 17 00:00:00 2001 From: DNT Date: Wed, 7 Aug 2024 10:59:31 +0700 Subject: [PATCH] fix: compare enum with strict --- src/EnumComparable.php | 5 ++--- src/EnumValueResolver.php | 14 ++++++++++---- tests/EnumCompareTest.php | 1 + 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/EnumComparable.php b/src/EnumComparable.php index eb24972..100a598 100644 --- a/src/EnumComparable.php +++ b/src/EnumComparable.php @@ -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; } diff --git a/src/EnumValueResolver.php b/src/EnumValueResolver.php index 49abe51..1f2acff 100644 --- a/src/EnumValueResolver.php +++ b/src/EnumValueResolver.php @@ -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); @@ -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) { diff --git a/tests/EnumCompareTest.php b/tests/EnumCompareTest.php index 6810600..b733856 100644 --- a/tests/EnumCompareTest.php +++ b/tests/EnumCompareTest.php @@ -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(); });