Completed
Pull Request — master (#6)
by Yann
07:34
created

EnumExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 1
b 0
f 1
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace EnumBundle\Twig\Extension;
4
5
use EnumBundle\Registry\EnumRegistryInterface;
6
use Twig_Extension;
7
8
/**
9
 * @author Yann Eugoné <[email protected]>
10
 */
11
class EnumExtension extends Twig_Extension
12
{
13
    /**
14
     * @var EnumRegistryInterface
15
     */
16
    private $registry;
17
18
    /**
19
     * @param EnumRegistryInterface $registry
20
     */
21 2
    public function __construct(EnumRegistryInterface $registry)
22
    {
23 2
        $this->registry = $registry;
24 2
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 2
    public function getFunctions()
30
    {
31
        return [
32 2
            new \Twig_SimpleFunction('enum_label', [ $this, 'getLabel' ]),
33 2
            new \Twig_SimpleFunction('enum_choices', [ $this, 'getChoices' ]),
34 2
        ];
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 2
    public function getFilters()
41
    {
42
        return [
43 2
            new \Twig_SimpleFilter('enum_label', [ $this, 'getLabel' ]),
44 2
        ];
45
    }
46
47
    /**
48
     * @param string $value
49
     * @param string $enum
50
     *
51
     * @return string
52
     */
53 1
    public function getLabel($value, $enum)
54
    {
55 1
        $choices = $this->getChoices($enum);
56
57 1
        if (isset($choices[$value])) {
58 1
            return $choices[$value];
59
        }
60
61 1
        return $value;
62
    }
63
64
    /**
65
     * @param string $enum
66
     *
67
     * @return array
68
     */
69 2
    public function getChoices($enum)
70
    {
71 2
        return $this->registry->get($enum)->getChoices();
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77 2
    public function getName()
78
    {
79 2
        return 'enum';
80
    }
81
}
82