Completed
Branch master (01610a)
by Arnaud
06:29
created

Collection::render()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 13

Duplication

Lines 4
Ratio 17.39 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 4
loc 23
ccs 0
cts 18
cp 0
rs 8.7972
cc 4
eloc 13
nc 5
nop 1
crap 20
1
<?php
2
3
namespace LAG\AdminBundle\Field\Field;
4
5
use LAG\AdminBundle\Field\EntityFieldInterface;
6
use LAG\AdminBundle\Field\Field;
7
use Symfony\Component\OptionsResolver\OptionsResolver;
8
use Symfony\Component\PropertyAccess\PropertyAccess;
9
use Twig_Environment;
10
11
class Collection extends Field implements EntityFieldInterface
12
{
13
    /**
14
     * @var Twig_Environment
15
     */
16
    protected $twig;
17
18
    /**
19
     * @var Field[]
20
     */
21
    protected $fields = [];
22
23
    /**
24
     * @var Object
25
     */
26
    protected $entity;
27
28
    /**
29
     * @param mixed $value
30
     * @return string
31
     */
32
    public function render($value)
33
    {
34
        $render = '';
35
        $accessor = PropertyAccess::createPropertyAccessorBuilder()
36
            ->enableMagicCall()
37
            ->getPropertyAccessor();
38
39
        foreach ($this->fields as $field) {
40
            $value = null;
41
            // if name starts with a underscore, it is a custom field, not mapped to the entity
42 View Code Duplication
            if (substr($field->getName(), 0, 1) != '_') {
43
                // get raw value from object
44
                $value = $accessor->getValue($this->entity, $field->getName());
45
            }
46
            // if the field required an entity to be rendered, we set it
47
            if ($field instanceof EntityFieldInterface) {
48
                $field->setEntity($this->entity);
49
            }
50
            $render .= $field->render($value);
51
        }
52
53
        return $render;
54
    }
55
56
    /**
57
     * @param OptionsResolver $resolver
58
     * @return void
59
     */
60
    public function configureOptions(OptionsResolver $resolver)
61
    {
62
        $resolver
63
            ->setRequired('fields')
64
            ->setAllowedTypes('fields', 'array');
65
    }
66
67
    /**
68
     * Set options values after options resolving.
69
     *
70
     * @param array $options
71
     *
72
     * @return mixed
73
     */
74
    public function setOptions(array $options)
75
    {
76
        $this->fields = $options['fields'];
77
    }
78
79
    public function getType()
80
    {
81
        return 'collection';
82
    }
83
84
    public function setTwig(Twig_Environment $twig)
85
    {
86
        $this->twig = $twig;
87
    }
88
89
    public function setEntity($entity)
90
    {
91
        $this->entity = $entity;
92
    }
93
}
94