Completed
Pull Request — master (#36)
by Maxime
01:42
created

EnumCaster   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 41
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B castEnum() 0 38 6
1
<?php
2
3
/*
4
 * This file is part of the "elao/enum" package.
5
 *
6
 * Copyright (C) 2016 Elao
7
 *
8
 * @author Elao <[email protected]>
9
 */
10
11
namespace Elao\Enum\Bridge\Symfony\VarDumper\Caster;
12
13
use Elao\Enum\EnumInterface;
14
use Elao\Enum\FlaggedEnum;
15
use Elao\Enum\ReadableEnum;
16
use Symfony\Component\VarDumper\Caster\Caster;
17
use Symfony\Component\VarDumper\Caster\ConstStub;
18
19
final class EnumCaster
20
{
21
    public static function castEnum(EnumInterface $enum, $array)
22
    {
23
        $a = [];
24
        $value = $enum->getValue();
25
        $r = new \ReflectionClass($enum);
26
        $constants = $r->getConstants();
27
28
        if (PHP_VERSION_ID >= 70100) {
29
            $constants = array_filter($constants, function (string $k) use ($r) {
30
                return $r->getReflectionConstant($k)->isPublic();
31
            }, ARRAY_FILTER_USE_KEY);
32
        }
33
34
        $rConstants = array_flip($constants);
35
36
        // Append constant(s) name(s)
37
        $a[Caster::PREFIX_VIRTUAL . '⚑ '] = new ConstStub(implode(' | ', array_map(function ($v) use ($rConstants) {
38
            return $rConstants[$v];
39
        }, $enum instanceof FlaggedEnum && $enum->getFlags() ? $enum->getFlags() : (array) $value)), $value);
40
41
        // Append readable value
42
        if ($enum instanceof ReadableEnum) {
43
            $a[Caster::PREFIX_VIRTUAL . 'readable'] = $enum->getReadable();
44
        }
45
46
        // Append the instance value
47
        $a[Caster::PREFIX_PROTECTED . 'value'] = $value;
48
49
        // Append single bit flags list
50
        if ($enum instanceof FlaggedEnum) {
51
            $a[Caster::PREFIX_PROTECTED . 'flags'] = array_map(function (int $flag) use ($rConstants) {
52
                return new ConstStub($flag, $rConstants[$flag]);
53
            }, $enum->getFlags());
54
        }
55
56
        // Append any other potential properties
57
        return $a + $array;
58
    }
59
}
60