apie-lib /
value-objects
| 1 | <?php |
||
| 2 | |||
| 3 | |||
| 4 | namespace Apie\ValueObjects; |
||
| 5 | |||
| 6 | use ReflectionClass; |
||
| 7 | |||
| 8 | trait StringCaseInsensitiveEnumTrait |
||
| 9 | { |
||
| 10 | use StringTrait; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * @var string[] |
||
| 14 | */ |
||
| 15 | private static $lookupTable; |
||
| 16 | |||
| 17 | final protected function validValue(string $value): bool |
||
| 18 | { |
||
| 19 | $value = strtoupper($value); |
||
| 20 | $values = self::getLookupTable(); |
||
| 21 | return isset($values[$value]); |
||
| 22 | } |
||
| 23 | |||
| 24 | final protected function sanitizeValue(string $value): string |
||
| 25 | { |
||
| 26 | $value = strtoupper($value); |
||
| 27 | $values = self::getLookupTable(); |
||
| 28 | assert(isset($values[$value])); |
||
| 29 | return $values[$value]; |
||
| 30 | } |
||
| 31 | |||
| 32 | private static function getLookupTable(): array |
||
| 33 | { |
||
| 34 | if (!self::$lookupTable) { |
||
|
0 ignored issues
–
show
|
|||
| 35 | $values = self::getValidValues(); |
||
| 36 | self::$lookupTable = []; |
||
| 37 | foreach ($values as $value) { |
||
| 38 | self::$lookupTable[strtoupper($value)] = $value; |
||
| 39 | } |
||
| 40 | foreach ($values as $key => $value) { |
||
| 41 | self::$lookupTable[strtoupper($key)] = $value; |
||
| 42 | } |
||
| 43 | } |
||
| 44 | return self::$lookupTable; |
||
| 45 | } |
||
| 46 | |||
| 47 | final public static function getValidValues(): array |
||
| 48 | { |
||
| 49 | $reflectionClass = new ReflectionClass(__CLASS__); |
||
| 50 | return $reflectionClass->getConstants(); |
||
| 51 | } |
||
| 52 | } |
||
| 53 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.