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 str_contains; |
14
|
|
|
use function ucfirst; |
15
|
|
|
|
16
|
|
|
trait HasFormFields |
17
|
|
|
{ |
18
|
|
|
public function populate(FormInterface $form): void |
19
|
|
|
{ |
20
|
|
|
$data = $form->getValues(true); |
21
|
|
|
$mirror = new ReflectionClass($this); |
22
|
|
|
$properties = $mirror->getProperties(); |
23
|
|
|
|
24
|
|
|
foreach ($properties as $property) { |
25
|
|
|
$fieldName = $property->getName(); |
26
|
|
|
$attributes = $property->getAttributes(Field::class); |
27
|
|
|
|
28
|
|
|
if (count($attributes) > 0) { |
29
|
|
|
$rules = $attributes[0]->newInstance()->rules; |
30
|
|
|
|
31
|
|
|
if (str_contains($rules, '|')) { |
32
|
|
|
$rules = explode('|', $rules); |
33
|
|
|
$fieldType = array_shift($rules); |
34
|
|
|
} else { |
35
|
|
|
$fieldType = $rules; |
36
|
|
|
$rules = []; |
|
|
|
|
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if (str_contains($fieldType, 'date_format')) { |
40
|
|
|
$fieldType = str_contains($fieldType, 'H:i') |
41
|
|
|
? 'datetime' |
42
|
|
|
: 'date'; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$value = $data[$fieldName]; |
46
|
|
|
$this->setField($fieldName, $fieldType, $value); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function setField(string $fieldName, string $fieldType, mixed $value): void |
52
|
|
|
{ |
53
|
|
|
$setter = 'set' . ucfirst($fieldName); |
54
|
|
|
|
55
|
|
|
switch ($fieldType) { |
56
|
|
|
case 'checkbox': |
57
|
|
|
$this->$setter((bool) $value); |
58
|
|
|
break; |
59
|
|
|
case 'email': |
60
|
|
|
case 'file': |
61
|
|
|
case 'hidden': |
62
|
|
|
case 'password': |
63
|
|
|
case 'string': |
64
|
|
|
case 'text': |
65
|
|
|
case 'textarea': |
66
|
|
|
$this->$setter((string) $value); |
67
|
|
|
break; |
68
|
|
|
case 'integer': |
69
|
|
|
$this->$setter((int) $value); |
70
|
|
|
break; |
71
|
|
|
case 'float': |
72
|
|
|
$this->$setter((float) $value); |
73
|
|
|
break; |
74
|
|
|
case 'date': |
75
|
|
|
case 'datetime': |
76
|
|
|
case 'multiselect': |
77
|
|
|
case 'radio': |
78
|
|
|
case 'select': |
79
|
|
|
default: |
80
|
|
|
$this->$setter($value); |
81
|
|
|
break; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|