-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #32 from robmilward/feature/enum-trait
Add Enum trait
- Loading branch information
Showing
2 changed files
with
105 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<?php | ||
|
||
namespace LangleyFoxall\Helpers\Traits; | ||
|
||
trait Enum | ||
{ | ||
/** | ||
* Returns an array of all constants defined within the class. | ||
* | ||
* @return array | ||
*/ | ||
public static function all(): array | ||
{ | ||
try { | ||
$reflection = new \ReflectionClass(self::class); | ||
|
||
return array_values($reflection->getConstants()); | ||
} catch (\ReflectionException $e) { | ||
// This will never happen as the function can only ever be executed in a context where self::class is valid. | ||
return []; | ||
} | ||
} | ||
|
||
/** | ||
* Returns a bool indicating whether or not a value is present in the class. | ||
* | ||
* @param string $value | ||
* | ||
* @return bool | ||
*/ | ||
public static function valid(string $value): bool | ||
{ | ||
return array_search($value, self::all()) !== false; | ||
} | ||
} |