| Total Complexity | 6 |
| Total Lines | 58 |
| Duplicated Lines | 0 % |
| Coverage | 71.43% |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 5 | abstract class Enum |
||
| 6 | { |
||
| 7 | protected $value; |
||
| 8 | |||
| 9 | 2 | private function __construct($value) |
|
| 10 | { |
||
| 11 | 2 | $this->checkValueIsValid($value); |
|
| 12 | 1 | $this->value = $value; |
|
| 13 | 1 | } |
|
| 14 | |||
| 15 | /** |
||
| 16 | * @param $value |
||
| 17 | * @return static |
||
| 18 | */ |
||
| 19 | 2 | public static function fromValue($value) |
|
| 20 | { |
||
| 21 | 2 | return new static($value); |
|
| 22 | } |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Returns value. |
||
| 26 | * |
||
| 27 | * Override this method to strict type your Enum. |
||
| 28 | * |
||
| 29 | * @return mixed |
||
| 30 | */ |
||
| 31 | public function value() |
||
| 34 | } |
||
| 35 | |||
| 36 | public abstract function allowedValues(): array; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Checks whether the value is valid for this Enum. |
||
| 40 | * |
||
| 41 | * Override this method to add other validations. |
||
| 42 | * |
||
| 43 | * @param $value |
||
| 44 | */ |
||
| 45 | 2 | protected function checkValueIsValid($value): void |
|
| 46 | { |
||
| 47 | 2 | if (!in_array($value, $this->allowedValues())) { |
|
| 48 | 1 | throw new \InvalidArgumentException($this->valueNotValidMessage($value)); |
|
| 49 | } |
||
| 50 | 1 | } |
|
| 51 | |||
| 52 | /** |
||
| 53 | * Generates the error message. |
||
| 54 | * |
||
| 55 | * Override this method if the validation is ok but you want a different message. |
||
| 56 | * |
||
| 57 | * @param $value |
||
| 58 | * @return string |
||
| 59 | */ |
||
| 60 | protected function valueNotValidMessage($value): string |
||
| 63 | } |
||
| 64 | } |
||
| 65 |