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

EnumToArray   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
eloc 12
c 2
b 1
f 0
dl 0
loc 51
ccs 14
cts 15
cp 0.9333
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A names() 0 3 1
A getDisplayNamesArray() 0 14 3
A values() 0 3 1
A getAllDisplayNames() 0 4 1
A toArray() 0 3 1
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