1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Common\Trait; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Source: https://stackoverflow.com/a/71680007/9013718. |
7
|
|
|
*/ |
8
|
|
|
trait EnumToArray |
9
|
|
|
{ |
10
|
3 |
|
public static function names(): array |
11
|
|
|
{ |
12
|
3 |
|
return array_column(self::cases(), 'name'); |
13
|
|
|
} |
14
|
|
|
|
15
|
24 |
|
public static function values(): array |
16
|
|
|
{ |
17
|
24 |
|
return array_column(self::cases(), 'value'); |
18
|
|
|
} |
19
|
|
|
|
20
|
3 |
|
public static function toArray(): array |
21
|
|
|
{ |
22
|
3 |
|
return array_combine(self::values(), self::names()); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Creates an array with the enum values as keys and the translated names as values. |
27
|
|
|
* Requires the getDisplayName method to be implemented in the enum. |
28
|
|
|
* |
29
|
|
|
* @return array |
30
|
|
|
*/ |
31
|
12 |
|
public static function getAllDisplayNames(): array |
32
|
|
|
{ |
33
|
|
|
// Creates an array by using one array for keys and another for its values |
34
|
12 |
|
return array_combine(self::values(), self::getDisplayNamesArray(self::cases())); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Returns array with all enum values as names that can be displayed by the frontend. |
39
|
|
|
* Requires the getDisplayName() method to be implemented in the enum. |
40
|
|
|
* |
41
|
|
|
* @param self[] $enumCases |
42
|
|
|
* |
43
|
|
|
* @return array |
44
|
|
|
*/ |
45
|
12 |
|
private static function getDisplayNamesArray(array $enumCases): array |
46
|
|
|
{ |
47
|
12 |
|
$displayNames = []; |
48
|
12 |
|
foreach ($enumCases as $enumCase) { |
49
|
|
|
// If the enum case has a getDisplayName method, use it to get the display name otherwise use the case name |
50
|
|
|
/** @phpstan-ignore-next-line https://github.com/phpstan/phpstan/issues/7599 */ |
51
|
12 |
|
if (method_exists($enumCase, 'getDisplayName')) { |
52
|
12 |
|
$displayNames[] = $enumCase->getDisplayName(); |
53
|
|
|
} else { |
54
|
|
|
$displayNames[] = $enumCase->name; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
12 |
|
return $displayNames; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|