Completed
Push — master ( 15d7d3...76d300 )
by Zachary
01:42
created

Meta::isValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace ZingleCom\Enum;
4
5
use phootwork\collection\Map;
6
use phootwork\collection\Set;
7
use ZingleCom\Enum\Exception\MissingValueException;
8
use ZingleCom\Enum\Exception\SizeMismatchException;
9
10
/**
11
 * Class Meta
12
 *
13
 * Contains meta data for enum class like constants
14
 * of the class, values, and some methods to access
15
 * that data inflected from the class.
16
 */
17
class Meta implements MetaInterface
18
{
19
    /**
20
     * @var Map
21
     */
22
    private $constants;
23
24
    /**
25
     * @var Set
26
     */
27
    private $values;
28
29
30
    /**
31
     * Meta constructor.
32
     *
33
     * @param array $constants
34
     *
35
     * @throws SizeMismatchException
36
     */
37
    public function __construct(array $constants)
38
    {
39
        $this->constants = new Map($constants);
40
        $this->values    = new Set($this->constants->values()->toArray());
41
42
        if ($this->constants->keys()->size() !== $this->values->size()) {
43
            throw new SizeMismatchException();
44
        }
45
    }
46
47
    /**
48
     * @param mixed $value
49
     * @return bool
50
     */
51
    public function isValid($value): bool
52
    {
53
        return $this->values->contains($value);
54
    }
55
56
    /**
57
     * @param mixed $value
58
     * @return string
59
     * @throws MissingValueException
60
     */
61
    public function getConstantName($value): string
62
    {
63
        $flipped = array_flip($this->constants->toArray());
64
        if (!isset($flipped[$value])) {
65
            throw new MissingValueException($value);
66
        }
67
68
        return $flipped[$value];
69
    }
70
71
    /**
72
     * @return Map
73
     */
74
    public function getConstants(): Map
75
    {
76
        return $this->constants;
77
    }
78
}
79