Passed
Push — master ( 8ff4e3...ffee1f )
by Samuel
03:00
created

EnumToArray::prettifyNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 4
c 2
b 1
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
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