Created
April 16, 2019 10:53
-
-
Save kobus1998/5c30e0b8bc100230df6b976c5ed6a4d4 to your computer and use it in GitHub Desktop.
Enum in php
This file contains hidden or 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
| <?php | |
| abstract class Enum | |
| { | |
| /** | |
| * @var array | |
| */ | |
| private static $constCacheArray = null; | |
| /** | |
| * Get constants | |
| * | |
| * @return array | |
| */ | |
| private static function getConstants() | |
| { | |
| if (self::$constCacheArray == null) { | |
| self::$constCacheArray = []; | |
| } | |
| $calledClass = get_called_class(); | |
| if (!array_key_exists($calledClass, self::$constCacheArray)) { | |
| $reflect = new ReflectionClass($calledClass); | |
| self::$constCacheArray[$calledClass] = $reflect->getConstants(); | |
| } | |
| return self::$constCacheArray[$calledClass]; | |
| } | |
| /** | |
| * Check name valid | |
| * | |
| * @param string $name | |
| * @param boolean $strict | |
| * @return boolean | |
| */ | |
| public static function isValidName(string $name, bool $strict = false) | |
| { | |
| $constants = self::getConstants(); | |
| if ($strict) { | |
| return array_key_exists($name, $constants); | |
| } | |
| $keys = array_map('strtolower', array_keys($constants)); | |
| return in_array(strtolower($name), $keys); | |
| } | |
| /** | |
| * Check value valid | |
| * | |
| * @param mixed $value | |
| * @param boolean $strict | |
| * @return boolean | |
| */ | |
| public static function isValidValue($value, bool $strict = true) | |
| { | |
| $values = array_values(self::getConstants()); | |
| return in_array($value, $values, $strict); | |
| } | |
| } | |
| class DaysOfWeek extends Enum | |
| { | |
| const Sunday = 0; | |
| const Monday = 1; | |
| const Tuesday = 2; | |
| const Wednesday = 3; | |
| const Thursday = 4; | |
| const Friday = 5; | |
| const Saturday = 6; | |
| } | |
| var_dump( | |
| DaysOfWeek::isValidName('Humpday'), | |
| DaysOfWeek::isValidName('Monday'), | |
| DaysOfWeek::isValidName('monday'), | |
| DaysOfWeek::isValidName('monday', true), | |
| DaysOfWeek::isValidName(0), | |
| DaysOfWeek::isValidValue(0), | |
| DaysOfWeek::isValidValue(5), | |
| DaysOfWeek::isValidValue(7), | |
| DaysOfWeek::isValidValue('Friday') | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment