Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ abstract class Enum implements JsonSerializable
/** @var string */
protected $value;

/**
* @param string $value
*
* @return static
*/
public static function from(string $value): Enum
{
if (method_exists(static::class, $value)) {
Expand All @@ -37,6 +42,10 @@ public function __construct(string $value = null)
throw new TypeError("Value {$value} not available in enum ".static::class);
}

if ($value === null) {
throw new TypeError("Value of enum can't be null");
}

$this->value = $value;
}

Expand Down Expand Up @@ -73,9 +82,13 @@ public function equals($enum): bool
return true;
}

/**
* @param \Spatie\Enum\Enum[] $enums
*
* @return bool
*/
public function isOneOf(array $enums): bool
{
/** @var \Spatie\Enum\Enum $enum */
foreach ($enums as $enum) {
if ($this->equals($enum)) {
return true;
Expand Down Expand Up @@ -112,14 +125,14 @@ public static function getValues(): array

protected static function resolve(): array
{
$enumValues = [];

$class = static::class;

if (isset(self::$cache[$class])) {
return self::$cache[$class];
}

$enumValues = [];

$staticReflection = new ReflectionClass(static::class);

foreach (self::resolveValuesFromStaticMethods($staticReflection) as $value => $name) {
Expand All @@ -130,15 +143,11 @@ protected static function resolve(): array
$enumValues[$value] = $name;
}

self::$cache[$class] = $enumValues;

return self::$cache[$class];
return self::$cache[$class] = $enumValues;
}

protected static function resolveValuesFromStaticMethods(ReflectionClass $staticReflection): array
{
$enumValues = [];

$selfReflection = new ReflectionClass(self::class);

$selfStaticMethods = [];
Expand All @@ -147,6 +156,7 @@ protected static function resolveValuesFromStaticMethods(ReflectionClass $static
$selfStaticMethods[$method->name] = $method->name;
}

$enumValues = [];
foreach ($staticReflection->getMethods(ReflectionMethod::IS_STATIC) as $method) {
$methodName = $method->getName();

Expand Down