Enum::toArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Kambo\Enum;
4
5
/**
6
 * Base class for enumeration.
7
 * Enum is created by extending this class and adding class constants.
8
 *
9
 * @author   Bohuslav Simek <[email protected]>
10
 * @license  MIT
11
 * @package  Kambo\Enum
12
 */
13
abstract class Enum
14
{
15
    /**
16
     * Store existing constants in a static cache per object.
17
     *
18
     * @var array
19
     */
20
    private static $cache = [];
21
22
    /**
23
     * Returns instances of the Enum class of all Enum constants
24
     *
25
     * @return array Constant name in key, Enum instance in value
26
     */
27 1
    public static function values()
28
    {
29 1
        return self::toArray();
30
    }
31
32
    /**
33
     * Returns all possible values as an array
34
     *
35
     * @return array Constant name in key, constant value in value
36
     */
37 3
    public static function toArray()
38
    {
39 3
        $class = get_called_class();
40 3
        if (!array_key_exists($class, self::$cache)) {
41 1
            $reflection          = new \ReflectionClass($class);
42 1
            self::$cache[$class] = $reflection->getConstants();
43 1
        }
44
45 3
        return self::$cache[$class];
46
    }
47
48
    /**
49
     * Check if a value is in enum
50
     *
51
     * @return boolean True if the value is in enum false if not
52
     */
53 1
    public static function inEnum($value)
54
    {
55 1
        $allItems = array_flip(self::toArray());
56
57 1
        return isset($allItems[$value]) ? true : false;
58
    }
59
}
60