Enum.php
5 years ago
EnumInterface.php
5 years ago
LogCategory.php
5 years ago
LogType.php
5 years ago
Enum.php
109 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Log\ValueObjects; |
| 4 | |
| 5 | use Give\Framework\Exceptions\Primitives\InvalidArgumentException; |
| 6 | use ReflectionClass; |
| 7 | use ReflectionException; |
| 8 | |
| 9 | /** |
| 10 | * Class ValueObject |
| 11 | * @package Give\Log\ValueObjects |
| 12 | * |
| 13 | * @since 2.10.0 |
| 14 | */ |
| 15 | abstract class Enum implements EnumInterface { |
| 16 | /** |
| 17 | * @var mixed |
| 18 | */ |
| 19 | protected $value; |
| 20 | |
| 21 | /** |
| 22 | * ValueObject constructor. |
| 23 | * |
| 24 | * @param mixed $value |
| 25 | */ |
| 26 | public function __construct( $value ) { |
| 27 | if ( $value instanceof static ) { |
| 28 | $value = $value->getValue(); |
| 29 | } |
| 30 | |
| 31 | if ( ! self::isValid( $value ) ) { |
| 32 | throw new InvalidArgumentException( |
| 33 | sprintf( 'Invalid %s enumeration value provided %s', static::class, $value ) |
| 34 | ); |
| 35 | } |
| 36 | |
| 37 | $this->value = strtoupper( $value ); |
| 38 | } |
| 39 | |
| 40 | |
| 41 | /** |
| 42 | * Get an array of defined constants |
| 43 | * |
| 44 | * @return array |
| 45 | */ |
| 46 | public static function getAll() { |
| 47 | |
| 48 | static $constants = []; |
| 49 | |
| 50 | if ( ! isset( $constants[ static::class ] ) ) { |
| 51 | try { |
| 52 | $reflection = new ReflectionClass( static::class ); |
| 53 | $constants[ static::class ] = $reflection->getConstants(); |
| 54 | } catch ( ReflectionException $exception ) { |
| 55 | return []; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return $constants[ static::class ]; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * @inheritDoc |
| 64 | */ |
| 65 | public function getValue() { |
| 66 | $constants = self::getAll(); |
| 67 | |
| 68 | if ( isset( $constants[ $this->value ] ) ) { |
| 69 | return $constants[ $this->value ]; |
| 70 | } |
| 71 | |
| 72 | return null; |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Check if value is valid |
| 77 | * |
| 78 | * @param string $value |
| 79 | * @return bool |
| 80 | */ |
| 81 | public static function isValid( $value ) { |
| 82 | return array_key_exists( |
| 83 | strtoupper( $value ), |
| 84 | self::getAll() |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * @inheritDoc |
| 90 | */ |
| 91 | public function equalsTo( $value ) { |
| 92 | return $value instanceof self && $this->getValue() === $value->getValue(); |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * @param string $name |
| 97 | * @param array $args |
| 98 | * |
| 99 | * @return static |
| 100 | */ |
| 101 | public static function __callStatic( $name, $args ) { |
| 102 | if ( self::isValid( $name ) ) { |
| 103 | return new static( $name ); |
| 104 | } |
| 105 | |
| 106 | throw new InvalidArgumentException( "Invalid argument, does not match constant {$name}" ); |
| 107 | } |
| 108 | } |
| 109 |