Completed
Push — master ( 25a9e3...b9326f )
by Propa
02:22
created

FormBuilder::label()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4286
cc 3
eloc 6
nc 3
nop 1
1
<?php namespace Propaganistas\LaravelTranslatableBootForms\Form;
2
3
use AdamWathan\Form\Elements\Label;
4
use AdamWathan\Form\FormBuilder as _FormBuilder;
5
6
class FormBuilder extends _FormBuilder
7
{
8
9
    /**
10
     * Array of locale keys.
11
     *
12
     * @var array
13
     */
14
    protected $locales;
15
16
    /**
17
     * Since $model is a private property in the parent class, we need to define the model in this child class as well.
18
     * {@inheritdoc}
19
     */
20
    protected $model;
21
22
    /**
23
     * Sets the available locales for translatable fields.
24
     *
25
     * @param array $locales
26
     */
27
    public function setLocales(array $locales)
28
    {
29
        $this->locales = $locales;
30
    }
31
32
    /**
33
     * Since $model is a private property in the parent class, we need to bind the model in this child class as well.
34
     * {@inheritdoc}
35
     *
36
     */
37
    public function bind($model)
38
    {
39
        $this->model = is_array($model) ? (object) $model : $model;
40
        parent::bind($model);
41
    }
42
43
    /**
44
     * Since $model is a private property in the parent class, we need to unbind the model in this child class as well.
45
     * {@inheritdoc}
46
     *
47
     */
48
    protected function unbindModel()
49
    {
50
        $this->model = null;
51
        parent::unbindModel();
52
    }
53
54
    /**
55
     * Getting value from Model or ModelTranslation to populate form.
56
     * Courtesy of TypiCMS/TranslatableBootForms (https://github.com/TypiCMS/TranslatableBootForms/blob/master/src/TranslatableFormBuilder.php)
57
     *
58
     * @param string $name key
59
     * @return string value
60
     */
61
    protected function getModelValue($name)
62
    {
63
        $inputName = preg_split('/[\[\]]+/', $name, - 1, PREG_SPLIT_NO_EMPTY);
64
        if (count($inputName) == 2 && in_array($inputName[0], $this->locales)) {
65
            list($lang, $name) = $inputName;
66
            $value = isset($this->model->translate($lang)->{$name})
67
                ? $this->model->translate($lang)->{$name}
68
                : '';
69
70
            return $this->escape($value);
71
        }
72
73
        return $this->escape($this->model->{$name});
74
    }
75
}