Completed
Push — master ( c55d6b...4b2e15 )
by Elf
05:02
created

Enum::value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
ccs 0
cts 8
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Laravel\Support;
4
5
use Illuminate\Support\Arr;
6
use MyCLabs\Enum\Enum as PhpEnum;
7
use ElfSundae\Laravel\Support\Traits\EnumDefaultKey;
8
use ElfSundae\Laravel\Support\Traits\EnumTransferKeys;
9
10
abstract class Enum extends PhpEnum
11
{
12
    use EnumTransferKeys, EnumDefaultKey;
13
14
    /**
15
     * Get the key for the given value.
16
     *
17
     * @param  mixed  $value
18
     * @return mixed
19
     */
20
    public static function key($value)
21
    {
22
        return static::search($value);
23
    }
24
25
    /**
26
     * Get the value for the given key.
27
     *
28
     * @param  mixed  $key
29
     * @return mixed
30
     */
31
    public static function value($key)
32
    {
33
        return Arr::get(
34
            static::toArray(),
35
            static::getOriginalKey($key),
36
            static::defaultValue()
37
        );
38
    }
39
40
    /**
41
     * Get all values.
42
     *
43
     * @return array
44
     */
45
    public static function allValues()
46
    {
47
        return array_values(static::toArray());
48
    }
49
50
    /**
51
     * Get all keys.
52
     *
53
     * @return array
54
     */
55
    public static function allKeys()
56
    {
57
        return array_map(function ($key) {
58
            return static::getTransferredKey($key);
59
        }, static::keys());
60
    }
61
62
    /**
63
     * Get the key for the given value.
64
     *
65
     * @param  mixed  $value
66
     * @return mixed
67
     */
68
    public static function search($value)
69
    {
70
        $key = parent::search($value);
71
72
        if ($key === false) {
73
            $key = static::defaultKey();
74
        }
75
76
        return static::getTransferredKey($key);
77
    }
78
79
    /**
80
     * Check if is valid enum key.
81
     *
82
     * @param  mixed  $key
83
     * @return bool
84
     */
85
    public static function isValidKey($key)
86
    {
87
        return parent::isValidKey(static::getOriginalKey($key));
88
    }
89
90
    /**
91
     * Returns a value when called statically like so:
92
     * MyEnum::SOME_VALUE() given SOME_VALUE is a class constant
93
     *
94
     * @param  string  $name
95
     * @param  array  $arguments
96
     * @return static
97
     */
98
    public static function __callStatic($name, $arguments)
99
    {
100
        return new static(static::value($name));
101
    }
102
}
103