Enum.php
72 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\Support\ValueObjects; |
| 4 | |
| 5 | use BadMethodCallException; |
| 6 | use Give\Framework\Support\Facades\Str; |
| 7 | |
| 8 | /** |
| 9 | * @method public getKeyAsCamelCase() |
| 10 | */ |
| 11 | abstract class Enum extends \MyCLabs\Enum\Enum |
| 12 | { |
| 13 | /** |
| 14 | * @since 2.20.0 |
| 15 | * |
| 16 | * Adds support for is{Value} methods. So if an Enum has an ACTIVE value, then an isActive() instance method is |
| 17 | * automatically available. |
| 18 | * |
| 19 | * @param $name |
| 20 | * @param $arguments |
| 21 | * |
| 22 | * @return bool |
| 23 | */ |
| 24 | public function __call($name, $arguments) |
| 25 | { |
| 26 | if (strpos($name, 'is') === 0) { |
| 27 | $constant = Str::upper(Str::snake(Str::after($name, 'is'))); |
| 28 | |
| 29 | if ( ! self::hasConstant($constant)) { |
| 30 | throw new BadMethodCallException("$name does not match a corresponding enum constant."); |
| 31 | } |
| 32 | |
| 33 | return $this->equals(parent::$constant()); |
| 34 | } |
| 35 | |
| 36 | throw new BadMethodCallException("Method $name does not exist on enum"); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * @param ...$enums |
| 41 | * |
| 42 | * @return bool |
| 43 | */ |
| 44 | public function isOneOf(...$enums) { |
| 45 | foreach($enums as $enum) { |
| 46 | if ( $this->equals($enum) ) { |
| 47 | return true; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | return false; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * @return string |
| 56 | */ |
| 57 | public function getKeyAsCamelCase() |
| 58 | { |
| 59 | return Str::camel($this->getKey()); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * @param string $name |
| 64 | * |
| 65 | * @return bool |
| 66 | */ |
| 67 | protected static function hasConstant($name) |
| 68 | { |
| 69 | return array_key_exists($name, static::toArray()); |
| 70 | } |
| 71 | } |
| 72 |