HasFormFields   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 18
eloc 42
c 1
b 0
f 0
dl 0
loc 58
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C setField() 0 29 14
A populate() 0 23 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Del\Form\Traits;
6
7
use Del\Form\Field\Attributes\Field;
8
use Del\Form\FormInterface;
9
use ReflectionClass;
10
use function array_shift;
11
use function count;
12
use function explode;
13
use function ucfirst;
14
15
trait HasFormFields
16
{
17
    public function populate(FormInterface $form): void
18
    {
19
        $data = $form->getValues();
20
        $mirror = new ReflectionClass($this);
21
        $properties = $mirror->getProperties();
22
23
        foreach ($properties as $property) {
24
            $fieldName = $property->getName();
25
            $attributes = $property->getAttributes(Field::class);
26
27
            if (count($attributes) > 0) {
28
                $rules = $attributes[0]->newInstance()->rules;
29
30
                if (strpos($rules, '|') !== false) {
31
                    $rules = explode('|', $rules);
32
                    $fieldType = array_shift($rules);
33
                } else {
34
                    $fieldType = $rules;
35
                    $rules = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $rules is dead and can be removed.
Loading history...
36
                }
37
38
                $value = $data[$fieldName];
39
                $this->setField($fieldName, $fieldType, $value);
40
            }
41
        }
42
    }
43
44
    private function setField(string $fieldName, string $fieldType, mixed $value): void
45
    {
46
        $setter = 'set' . ucfirst($fieldName);
47
48
        switch ($fieldType) {
49
            case 'checkbox':
50
                $this->$setter((bool) $value);
51
                break;
52
            case 'email':
53
            case 'file':
54
            case 'hidden':
55
            case 'password':
56
            case 'string':
57
            case 'text':
58
            case 'textarea':
59
                $this->$setter((string) $value);
60
                break;
61
            case 'integer':
62
                $this->$setter((int) $value);
63
                break;
64
            case 'float':
65
                $this->$setter((float) $value);
66
                break;
67
            case 'multiselect':
68
            case 'radio':
69
            case 'select':
70
            default:
71
                $this->$setter($value);
72
                break;
73
        }
74
    }
75
}
76