loophp /
phposinfo
| 1 | <?php |
||
| 2 | |||
| 3 | /** |
||
| 4 | * For the full copyright and license information, please view |
||
| 5 | * the LICENSE file that was distributed with this source code. |
||
| 6 | */ |
||
| 7 | |||
| 8 | declare(strict_types=1); |
||
| 9 | |||
| 10 | namespace loophp\phposinfo\Enum; |
||
| 11 | |||
| 12 | use Exception; |
||
| 13 | use Generator; |
||
| 14 | use ReflectionClass; |
||
| 15 | use ReflectionException; |
||
| 16 | |||
| 17 | use function constant; |
||
| 18 | |||
| 19 | abstract class Enum |
||
| 20 | { |
||
| 21 | /** |
||
| 22 | * @return Generator<int|string> |
||
| 23 | */ |
||
| 24 | 4 | final public static function getIterator(): Generator |
|
| 25 | { |
||
| 26 | 4 | $reflection = null; |
|
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 27 | |||
| 28 | try { |
||
| 29 | 4 | $reflection = new ReflectionClass(static::class); |
|
| 30 | } catch (ReflectionException) { |
||
| 31 | // Do something. |
||
| 32 | } |
||
| 33 | |||
| 34 | 4 | if (null !== $reflection) { |
|
| 35 | 4 | yield from $reflection->getConstants(); |
|
| 36 | } |
||
| 37 | 2 | } |
|
| 38 | |||
| 39 | 4 | final public static function has(string $key): bool |
|
| 40 | { |
||
| 41 | 4 | foreach (static::getIterator() as $keyConst => $valueConst) { |
|
| 42 | 4 | if ($key !== $keyConst) { |
|
| 43 | 4 | continue; |
|
| 44 | } |
||
| 45 | |||
| 46 | 4 | return true; |
|
| 47 | } |
||
| 48 | |||
| 49 | 2 | return false; |
|
| 50 | } |
||
| 51 | |||
| 52 | final public static function isValid(int|string $value): bool |
||
| 53 | { |
||
| 54 | foreach (static::getIterator() as $valueConst) { |
||
| 55 | 4 | if ($value !== $valueConst) { |
|
| 56 | continue; |
||
| 57 | 4 | } |
|
| 58 | 4 | ||
| 59 | 4 | return true; |
|
| 60 | } |
||
| 61 | |||
| 62 | 4 | return false; |
|
| 63 | } |
||
| 64 | |||
| 65 | 1 | /** |
|
| 66 | * @throws Exception |
||
| 67 | */ |
||
| 68 | final public static function key(int|string $value): string |
||
| 69 | { |
||
| 70 | foreach (static::getIterator() as $keyConst => $valueConst) { |
||
| 71 | if ($value === $valueConst) { |
||
| 72 | return $keyConst; |
||
| 73 | 4 | } |
|
| 74 | } |
||
| 75 | 4 | ||
| 76 | 4 | throw new Exception('No such key.'); |
|
| 77 | 4 | } |
|
| 78 | |||
| 79 | final public static function value(string $value): int|string |
||
| 80 | { |
||
| 81 | 1 | return constant('static::' . $value); |
|
| 82 | } |
||
| 83 | } |
||
| 84 |