This repository was archived by the owner on Mar 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormElement.php
More file actions
105 lines (92 loc) · 2.3 KB
/
FormElement.php
File metadata and controls
105 lines (92 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Cli\Component\Element;
use Ulrack\Cli\Common\Element\FormInterface;
use Ulrack\Cli\Common\Element\ElementInterface;
use Ulrack\Cli\Common\Element\Form\FieldInterface;
use Ulrack\Cli\Common\Element\Form\FieldValidatorInterface;
class FormElement implements FormInterface
{
/**
* Contains the elements to describe the form.
*
* @var ElementInterface[]
*/
private $description;
/**
* Contains the form data.
*
* @var mixed[]
*/
private $form = [];
/**
* Contains the fields of the form.
*
* @var FieldInterface[]
*/
private $fields = [];
/**
* Constructor.
*
* @param ElementInterface ...$description
*/
public function __construct(
ElementInterface ...$description
) {
$this->description = $description;
}
/**
* Adds a field to the form.
*
* @param string $name
* @param FieldInterface $field
* @param FieldValidatorInterface $validator
*
* @return void
*/
public function addField(
string $name,
FieldInterface $field,
FieldValidatorInterface $validator
): void {
$this->fields[$name] = [$field, $validator];
}
/**
* Processes the form and stores the input.
*
* @return void
*/
public function render(): void
{
foreach ($this->description as $element) {
$element->render();
}
$form = [];
foreach ($this->fields as $name => $fieldValidator) {
/** @var FieldInterface $field */
/** @var FieldValidatorInterface $validator */
[$field, $validator] = $fieldValidator;
$field->render();
$result = $field->getInput();
while (!$validator->__invoke($result)) {
$validator->getError()->render();
$field->render();
$result = $field->getInput();
}
$form[$name] = $result;
}
$this->form = $form;
}
/**
* Retrieves the input provided in the form.
*
* @return mixed[]
*/
public function getInput(): array
{
return $this->form;
}
}