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