mirror of
https://github.com/archtechx/enums.git
synced 2025-12-12 11:14:05 +00:00
Comparable enum (#20)
* feat: comparable enum * test: comparable enum * ci: php-cs-fixer in repository scope * chore: add `Comparable` usage in README * ci: globally use `php-cs-fixer` * improve Comparable logic * test more PHP versions in CI * update ci job name * remove class name quoting in exceptions to match PHP behavior * migrate pest config * add comment to test --------- Co-authored-by: Samuel Štancl <samuel@archte.ch> Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
This commit is contained in:
parent
fb521d2dcb
commit
f0ea4c36c8
9 changed files with 188 additions and 21 deletions
50
src/Comparable.php
Normal file
50
src/Comparable.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace ArchTech\Enums;
|
||||
|
||||
use Exception;
|
||||
use Iterator;
|
||||
use IteratorAggregate;
|
||||
|
||||
trait Comparable
|
||||
{
|
||||
public function is(mixed $enum): bool
|
||||
{
|
||||
return $this === $enum;
|
||||
}
|
||||
|
||||
public function isNot(mixed $enum): bool
|
||||
{
|
||||
return ! $this->is($enum);
|
||||
}
|
||||
|
||||
public function in(array|object $enums): bool
|
||||
{
|
||||
$iterator = $enums;
|
||||
|
||||
if (! is_array($enums)) {
|
||||
if ($enums instanceof Iterator) {
|
||||
$iterator = $enums;
|
||||
} elseif ($enums instanceof IteratorAggregate) {
|
||||
$iterator = $enums->getIterator();
|
||||
} else {
|
||||
throw new Exception('in() expects an iterable value');
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($iterator as $item) {
|
||||
if ($item === $this) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function notIn(array|object $enums): bool
|
||||
{
|
||||
return ! $this->in($enums);
|
||||
}
|
||||
}
|
||||
|
|
@ -37,7 +37,7 @@ trait From
|
|||
*/
|
||||
public static function fromName(string $case): static
|
||||
{
|
||||
return static::tryFromName($case) ?? throw new ValueError('"' . $case . '" is not a valid name for enum "' . static::class . '"');
|
||||
return static::tryFromName($case) ?? throw new ValueError('"' . $case . '" is not a valid name for enum ' . static::class . '');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue