FormFieldFactory::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace WebTheory\Saveyour\Factory;
4
5
use Exception;
6
use WebTheory\Factory\Traits\ClassResolverTrait;
7
use WebTheory\Factory\Traits\SmartFactoryTrait;
8
use WebTheory\Html\TagSage;
9
use WebTheory\Saveyour\Contracts\Factory\FormFieldResolverFactoryInterface;
10
use WebTheory\Saveyour\Contracts\Field\FormFieldInterface;
11
use WebTheory\Saveyour\Field\Type\Input;
12
13
class FormFieldFactory implements FormFieldResolverFactoryInterface
14
{
15
    use SmartFactoryTrait;
0 ignored issues
show
Bug introduced by
The trait WebTheory\Factory\Traits\SmartFactoryTrait requires the property $name which is not provided by WebTheory\Saveyour\Factory\FormFieldFactory.
Loading history...
16
    use ClassResolverTrait;
17
18
    private array $fields = [];
19
20
    protected array $namespaces = [];
21
22
    protected array $rules = [];
23
24
    public const NAMESPACES = [
25
        'webtheory.saveyour' => "WebTheory\\Saveyour\\Fields",
26
    ];
27
28
    public const FIELDS = [];
29
30
    protected const CONVENTION = null;
31
32
    public function __construct(array $namespaces = [], array $fields = [])
33
    {
34
        $this->namespaces = $namespaces + static::NAMESPACES;
35
        $this->fields = $fields + static::FIELDS;
36
    }
37
38
    public function getFields()
39
    {
40
        return $this->fields;
41
    }
42
43
    /**
44
     * @return $this
45
     */
46
    public function addField(string $arg, string $field): FormFieldFactory
47
    {
48
        $this->fields[$arg] = $field;
49
50
        return $this;
51
    }
52
53
    /**
54
     * @return $this
55
     */
56
    public function addFields(array $fields): FormFieldFactory
57
    {
58
        $this->fields = $fields + $this->fields;
59
60
        return $this;
61
    }
62
63
    public function create(string $field, array $args = []): FormFieldInterface
64
    {
65
        $class = $this->getClass($field);
66
67
        if (isset($this->fields[$field])) {
68
            $field = $this->build($this->fields[$field], $args);
69
        } elseif (false !== $class) {
70
            $field = $this->build($class, $args);
71
        } elseif (TagSage::isIt('standard_input_type', $field)) {
72
            $args['type'] = $field;
73
            $field = $this->build(Input::class, $args);
74
        } else {
75
            throw new Exception("{$field} is not a recognized field type");
76
        }
77
78
        return $field;
79
    }
80
}
81