Completed
Push — master ( 6b3ff5...5efdb1 )
by Anılcan
05:34
created

Former::make()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 3
1
<?php
2
3
namespace AnilcanCakir\Former;
4
5
use AnilcanCakir\Former\Contracts\Former as Contract;
6
use AnilcanCakir\Former\Contracts\FormerHelper as HelperContract;
7
use Illuminate\Database\Eloquent\Model;
8
9
/**
10
 * Class FormFactory.
11
 */
12
class Former implements Contract
13
{
14
    /**
15
     * The FormerHelper instance.
16
     *
17
     * @var HelperContract
18
     */
19
    private $helper;
20
21
    /**
22
     * FormFactory constructor.
23
     *
24
     * @param HelperContract $helper
25
     */
26
    public function __construct(HelperContract $helper)
27
    {
28
        $this->helper = $helper;
29
    }
30
31
    /**
32
     * Make a form instance by using the rules.
33
     *
34
     * @param array $formRules
35
     * @param Model|null $model
36
     * @param array $types
37
     * @return Form
38
     */
39
    public function make(array $formRules, Model $model = null, array $types = [])
40
    {
41
        $form = new Form(
42
            $model, $this->helper
43
        );
44
45
        foreach ($formRules as $name => $rules) {
46
            if (is_string($rules)) {
47
                $rules = explode('|', $rules);
48
            }
49
50
            $form->addField(
51
                $this->getInputByRulesAndTypes($name, $rules, $types),
52
                $name,
53
                $rules
54
            );
55
        }
56
57
        return $form;
58
    }
59
60
61
    /**
62
     * Make a form instance by using the form request.
63
     *
64
     * @param $formRequest
65
     * @param Model $model
66
     * @param array $types
67
     * @return Form
68
     */
69
    public function makeFromRequest($formRequest, Model $model, array $types = [])
70
    {
71
        // TODO: Implement makeFromRequest() method.
72
73
        return null;
74
    }
75
76
    /**
77
     * Get input class by rules and types for a field.
78
     *
79
     * @param string $name
80
     * @param string[] $rules
81
     * @param string[] $types
82
     * @return string
83
     */
84
    protected function getInputByRulesAndTypes($name, $rules, $types)
85
    {
86
        if (isset($types[$name])) {
87
            return $this->helper->getFieldClassFromType($types[$name]);
88
        }
89
90
        return $this->helper->getFieldClassFromRules($rules);
91
    }
92
}
93