FormLabelExtension   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 10
c 5
b 1
f 1
lcom 0
cbo 4
dl 0
loc 71
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getFunctions() 0 6 1
A prepareFormLabel() 0 20 3
B getLabelParts() 0 19 5
A getName() 0 4 1
1
<?php
2
3
namespace Saxulum\Crud\Twig;
4
5
use Saxulum\Crud\Util\Helper;
6
use Symfony\Component\Form\FormView;
7
8
class FormLabelExtension extends \Twig_Extension
9
{
10
    /**
11
     * @return array
12
     */
13
    public function getFunctions()
14
    {
15
        return array(
16
            new \Twig_SimpleFunction('prepareFormLabel', array($this, 'prepareFormLabel')),
17
        );
18
    }
19
20
    /**
21
     * @param FormView $formView
22
     *
23
     * @return string
24
     */
25
    public function prepareFormLabel(FormView $formView)
26
    {
27
        $labelParts = $this->getLabelParts($formView);
28
29
        if ($labelParts[0] === '') {
30
            $labelParts[0] = 'form';
31
        }
32
33
        // hack for main form: entity_edit, will be entity.edit
34
        $mainFormParts = explode('_', $labelParts[0]);
35
        unset($labelParts[0]);
36
37
        $labelParts = array_merge($mainFormParts, array('label'), $labelParts);
38
39
        foreach ($labelParts as $i => $labelPart) {
40
            $labelParts[$i] = Helper::camelCaseToUnderscore($labelPart);
41
        }
42
43
        return implode('.', $labelParts);
44
    }
45
46
    /**
47
     * @param FormView $formView
48
     *
49
     * @return array
50
     */
51
    protected function getLabelParts(FormView $formView)
52
    {
53
        $labelParts = array();
54
        $collection = false;
55
        do {
56
            $name = $formView->vars['name'];
57
            if (is_numeric($name) || $name === '__name__') {
58
                $collection = true;
59
            } else {
60
                if ($collection) {
61
                    $name .= '_collection';
62
                }
63
                $labelParts[] = $name;
64
                $collection = false;
65
            }
66
        } while ($formView = $formView->parent);
67
68
        return array_reverse($labelParts);
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    public function getName()
75
    {
76
        return 'form_label_extension';
77
    }
78
}
79