Completed
Push — master ( 0f5459...b9fce4 )
by Max
01:22
created

EnumTrait::value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
namespace drycart\data;
3
4
/*
5
 *  @copyright (c) 2019 Mendel <[email protected]>
6
 *  @license see license.txt
7
 */
8
9
/**
10
 * Abstract class for pretty use for list of constants and/or data arrays
11
 *
12
 * @author mendel
13
 */
14
trait EnumTrait
15
{
16
    /**
17
     * Array for titles. Just default dummy for override if need
18
     * @return array
19
     */
20
    static protected function titles() : array
21
    {
22
        return [];
23
    }
24
    
25
    /**
26
     * Main function. Return list of constants i.e. keys and values...
27
     * @return array
28
     */
29
    static public function data() : array
30
    {
31
        // @2DO: add assertion for check if values is uniqal
32
        $reflector = new \ReflectionClass(static::class);
33
        return $reflector->getConstants();
34
    }
35
    
36
    /**
37
     * Return all keys and his titles (defined at titles() or default generated)
38
     * @return array
39
     */
40
    static public function keyTitles() : array
41
    {
42
        $titles = static::titles();
43
        $result = [];
44
        foreach(array_keys(static::data()) as $key) {
45
            $result[$key] = $titles[$key] ?? StrHelper::key2Label(strtolower($key));
46
        }
47
        return $result;
48
    }
49
    
50
    /**
51
     * Return all values and his titles (defined at titles() or default generated)
52
     * @return array
53
     */
54
    static public function valueTitles() : array
55
    {
56
        $titles = static::titles();
57
        $result = [];
58
        foreach(static::data() as $key=>$value) {
59
            $result[$value] = $titles[$key] ?? StrHelper::key2Label(strtolower($key));
60
        }
61
        return $result;
62
    }
63
        
64
    /**
65
     * Get value by key
66
     * @param string $key
67
     * @return mixed
68
     */
69
    static public function value(string $key)
70
    {
71
        return static::data()[$key] ?? null;
72
    }
73
    
74
    /**
75
     * Get key by value
76
     * @param mixed $value
77
     * @return string|null
78
     */
79
    static public function key($value) : ?string
80
    {
81
        $data = array_flip(static::data());
82
        return $data[$value] ?? null;
83
    }
84
    
85
}
86