Generator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 7 2
A create() 0 22 5
1
<?php
2
3
namespace ZingleCom\Enum\Meta;
4
5
use phootwork\collection\Map;
6
use ZingleCom\Enum\AbstractEnum;
7
use ZingleCom\Enum\Exception\EnumException;
8
use ZingleCom\Enum\Meta;
9
use ZingleCom\Enum\MetaInterface;
10
11
/**
12
 * Class Generator
13
 */
14
class Generator implements GeneratorInterface
15
{
16
    /**
17
     * @var Map
18
     */
19
    private $meta;
20
21
22
    /**
23
     * MetaGenerator constructor.
24
     */
25
    public function __construct()
26
    {
27
        $this->meta = new Map();
28
    }
29
30
    /**
31
     * @param string|AbstractEnum $enumClass
32
     * @return MetaInterface
33
     * @throws EnumException
34
     */
35
    public function get(string $enumClass): MetaInterface
36
    {
37
        if (!$this->meta->has($enumClass)) {
38
            $this->meta->set($enumClass, $this->create($enumClass));
39
        }
40
41
        return $this->meta->get($enumClass);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->meta->get($enumClass) could return the type null which is incompatible with the type-hinted return ZingleCom\Enum\MetaInterface. Consider adding an additional type-check to rule them out.
Loading history...
42
    }
43
44
    /**
45
     * @param string $enumClass
46
     * @return MetaInterface
47
     * @throws EnumException
48
     */
49
    private function create(string $enumClass): MetaInterface
50
    {
51
        try {
52
            $refl = new \ReflectionClass($enumClass);
53
            if (!$refl->isSubclassOf(AbstractEnum::class)) {
54
                throw new EnumException(sprintf('Enum\'s must be of type %s', AbstractEnum::class));
55
            }
56
57
            $constants = [];
58
            $reflConstants = $refl->getReflectionConstants();
59
            foreach ($reflConstants as $reflConstant) {
60
                // don't add private constants to value value list.
61
                if ($reflConstant->isPrivate()) {
62
                    continue;
63
                }
64
65
                $constants[$reflConstant->getName()] = $reflConstant->getValue();
66
            }
67
68
            return new Meta($constants);
69
        } catch (\ReflectionException $e) {
70
            throw new EnumException($e->getMessage(), $e->getCode(), $e);
71
        }
72
    }
73
}
74