| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\Support\ValueObjects; |
| 4 |
|
| 5 |
use BadMethodCallException; |
| 6 |
use Give\Framework\Support\Facades\Str; |
| 7 |
|
| 8 |
/** |
| 9 |
* @since 2.10.0 |
| 10 |
*/ |
| 11 |
abstract class Enum extends BaseEnum |
| 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 |
* @since 2.20.0 |
| 41 |
*/ |
| 42 |
public function isOneOf(Enum...$enums): bool { |
| 43 |
foreach($enums as $enum) { |
| 44 |
if ( $this->equals($enum) ) { |
| 45 |
return true; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
return false; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* @since 2.20.0 |
| 54 |
*/ |
| 55 |
public function getKeyAsCamelCase(): string |
| 56 |
{ |
| 57 |
return Str::camel($this->getKey()); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @since 2.20.0 |
| 62 |
*/ |
| 63 |
protected static function hasConstant(string $name): bool |
| 64 |
{ |
| 65 |
return array_key_exists($name, static::toArray()); |
| 66 |
} |
| 67 |
} |
| 68 |
|