Skip to content

Commit

Permalink
minor #239 Simplify FlagBag guards (ogizanagi)
Browse files Browse the repository at this point in the history
This PR was merged into the 2.x-dev branch.

Discussion
----------

Simplify FlagBag guards

Fixes #238

Commits
-------

9bebd52 Simplify FlagBag guards
  • Loading branch information
ogizanagi committed Jan 20, 2025
2 parents 25382e9 + 9bebd52 commit d44e139
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions src/FlagBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,24 @@ public function __construct(string $enumType, int ...$bits)
}

/**
* @param class-string $enumType
* @param class-string|object $enumOrType
*
* @throws InvalidArgumentException If $enumType is not an int backed enum
* @throws InvalidArgumentException If $enumOrType is not an int backed enum
*/
private static function checkIntBackedEnumType(string $enumType): void
private static function checkIntBackedEnumType(string|object $enumOrType): void
{
if (!is_a($enumType, \BackedEnum::class, true)) {
throw new InvalidArgumentException(sprintf('"%s" is not a backed enum', $enumType));
if (!is_a($enumOrType, \BackedEnum::class, true)) {
throw new InvalidArgumentException(sprintf(
'"%s" is not a backed enum',
\is_object($enumOrType) ? $enumOrType::class : $enumOrType,
));
}

if ('int' !== (string) (new \ReflectionEnum($enumType))->getBackingType()) {
throw new InvalidArgumentException(sprintf('"%s" is not an int backed enum', $enumType));
if ('int' !== (string) (new \ReflectionEnum($enumOrType))->getBackingType()) {
throw new InvalidArgumentException(sprintf(
'"%s" is not an int backed enum',
\is_object($enumOrType) ? $enumOrType::class : $enumOrType,
));
}
}

Expand All @@ -84,18 +90,12 @@ public static function fromAll(string $enumType): FlagBag
*/
public static function from(string|\BackedEnum $enumOrType, \BackedEnum ...$flags): static
{
if ($enumOrType instanceof \BackedEnum) {
if ('int' !== (string) (new \ReflectionEnum($enumOrType))->getBackingType()) {
throw new InvalidArgumentException(sprintf('"%s" is not an int backed enum', $enumOrType::class));
}
self::checkIntBackedEnumType($enumOrType);

if ($enumOrType instanceof \BackedEnum) {
$type = $enumOrType::class;
$flags[] = $enumOrType;
} else {
if (!is_a($enumOrType, \BackedEnum::class, true)) {
throw new InvalidArgumentException(sprintf('"%s" is not a backed enum', $enumOrType));
}

$type = $enumOrType;
}

Expand Down

0 comments on commit d44e139

Please sign in to comment.