1
0
Fork 0
mirror of https://github.com/archtechx/enums.git synced 2025-12-12 15:54:04 +00:00

Issue #4: Added From trait (#7)

* #4 Added `From` trait

This adds the `from()` and `tryFrom()` methods to pure enums, and the `fromName()` and `tryFromName()` methods for all enum types.

* Code review changes

Dropped support for fragile indexes on pure enums

* Dropped unnecessary array_pop()

* import ValueError

* remove import

Co-authored-by: Samuel Štancl <samuel@archte.ch>
Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
This commit is contained in:
Samuel Levy 2022-03-24 07:18:58 +10:00 committed by GitHub
parent 0c87357a6e
commit cc5bba1912
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 183 additions and 2 deletions

55
src/From.php Normal file
View file

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace ArchTech\Enums;
use ValueError;
trait From
{
/**
* Gets the Enum by name, if it exists, for "Pure" enums.
*
* This will not override the `from()` method on BackedEnums
*
* @throws ValueError
*/
public static function from(string $case): static
{
return static::fromName($case);
}
/**
* Gets the Enum by name, if it exists, for "Pure" enums.
*
* This will not override the `tryFrom()` method on BackedEnums
*/
public static function tryFrom(string $case): ?static
{
return static::tryFromName($case);
}
/**
* Gets the Enum by name.
*
* @throws ValueError
*/
public static function fromName(string $case): static
{
return static::tryFromName($case) ?? throw new ValueError('"' . $case . '" is not a valid name for enum "' . static::class . '"');
}
/**
* Gets the Enum by name, if it exists.
*/
public static function tryFromName(string $case): ?static
{
$cases = array_filter(
static::cases(),
fn ($c) => $c->name === $case
);
return array_values($cases)[0] ?? null;
}
}