Completed
Push — develop ( d42c3f...ac22da )
by Freddie
02:15
created

FormBuilder::getTemplate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 19
rs 9.8333
eloc 13
nc 3
nop 0
1
<?php
2
3
namespace FlexPHP\Inputs\Builder;
4
5
use FlexPHP\Inputs\Input;
6
use Symfony\Component\Form\Extension\Core\Type\FormType;
7
use Symfony\Component\Form\FormBuilderInterface;
8
use Symfony\Component\Form\FormInterface;
9
use Symfony\Component\Form\Forms;
10
11
class FormBuilder extends AbstractBuilder
12
{
13
    private $data;
14
    private $inputs;
15
    private $template;
16
17
    public function __construct(
18
        string $name,
19
        array $inputs,
20
        array $data = null,
21
        array $options = [],
22
        string $template = null
23
    ) {
24
        $this->name = $name;
25
        $this->inputs = $this->parseInputs($inputs);
26
        $this->data = $data;
27
        $this->options = $options;
28
        $this->template = $template;
29
    }
30
31
    private function getInputs(): array
32
    {
33
        return $this->inputs;
34
    }
35
36
    private function getData(): ?array
37
    {
38
        return $this->data;
39
    }
40
41
    public function build(): FormInterface
42
    {
43
        return $this
44
            ->factory()
45
            ->getForm();
46
    }
47
48
    public function render(): string
49
    {
50
        return $this->twig()->createTemplate($this->getTemplate(), $this->getName())->render([
51
            'form' => $this->build()->createView(),
52
            'inputs' => $this->getInputs(),
53
        ]);
54
    }
55
56
    protected function factory(): FormBuilderInterface
57
    {
58
        return Forms::createFormFactory()->createBuilder(FormType::class, $this->getData(), $this->getOptions());
59
    }
60
61
    private function parseInputs($inputs): array
62
    {
63
        foreach ($inputs as $name => $options) {
64
            if (\is_array($options)) {
65
                $inputs[$name] = Input::create($options['type'] ?? 'text', $name, $options);
66
            }
67
        }
68
69
        return $inputs;
70
    }
71
72
    private function getTemplate(): string
73
    {
74
        $_template = <<<'T'
75
{{ form_start(form) }}
76
{% for input in inputs %}
77
    {{ input|raw }}
78
{% endfor %}
79
{{ form_end(form) }}
80
T;
81
82
        if ($this->template) {
83
            if (\is_file($this->template)) {
84
                $_template = \file_get_contents($this->template);
85
            } else {
86
                $_template = $this->template;
87
            }
88
        }
89
90
        return $_template;
91
    }
92
}
93