Passed
Push — master ( d855a0...34f20f )
by Enjoys
01:02 queued 12s
created

Form::getId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms;
6
7
use Closure;
8
use Enjoys\Forms\Elements\Csrf;
9
use Enjoys\Forms\Interfaces\DefaultsHandlerInterface;
10
use Enjoys\Forms\Traits;
11
use Enjoys\ServerRequestWrapper;
12
use Enjoys\ServerRequestWrapperInterface;
13
use Enjoys\Session\Session;
14
use Enjoys\Traits\Options;
15
use HttpSoft\ServerRequest\ServerRequestCreator;
16
use Webmozart\Assert\Assert;
17
18
use function strtoupper;
19
20
class Form
21
{
22
    use Traits\Attributes;
23
    use Options;
24
    use Traits\Container {
25
        addElement as private parentAddElement;
26
    }
27
28
    private const _ALLOWED_FORM_METHOD_ = ['GET', 'POST'];
29
30
    public const _TOKEN_CSRF_ = '_token_csrf';
31
    public const _TOKEN_SUBMIT_ = '_token_submit';
32
33
    public const ATTRIBUTES_DESC = '_desc_attributes_';
34
    public const ATTRIBUTES_VALIDATE = '_validate_attributes_';
35
    public const ATTRIBUTES_LABEL = '_label_attributes_';
36
    public const ATTRIBUTES_FIELDSET = '_fieldset_attributes_';
37
    public const ATTRIBUTES_FILLABLE_BASE = '_fillable_base_attributes_';
38
39
40
    private string $method = 'POST';
41
    private ?string $action = null;
42
    private ?string $id = null;
43
44
    private ServerRequestWrapperInterface $request;
45
    private DefaultsHandlerInterface $defaultsHandler;
46
47
    private bool $submitted = false;
48
    private Session $session;
49
50
    /**
51
     * @throws Exception\ExceptionRule
52
     */
53 86
    public function __construct(
54
        string $method = 'POST',
55
        string $action = null,
56
        string $id = null,
57
        ServerRequestWrapperInterface $request = null,
58
        DefaultsHandlerInterface $defaultsHandler = null,
59
        Session $session = null
60
    ) {
61 86
        $this->request = $request ?? new ServerRequestWrapper(ServerRequestCreator::createFromGlobals());
62 86
        $this->session = $session ?? new Session();
63 86
        $this->defaultsHandler = $defaultsHandler ?? new DefaultsHandler();
64
65 86
        $this->setMethod($method);
66 86
        $this->setAction($action);
67 86
        $this->setId($id);
68
69
    }
70
71
    /**
72
     * Возвращает true если форма отправлена и валидна.
73
     * На валидацию форма проверяется по умолчанию, если использовать параметр $validate
74
     * false, проверка будет только на отправку формы
75
     * @param bool $validate
76
     * @return bool
77
     */
78 4
    public function isSubmitted(bool $validate = true): bool
79
    {
80 4
        if ($this->submitted === false) {
81 1
            return false;
82
        }
83
84 3
        if ($validate !== false) {
85 2
            return Validator::check($this->getElements());
86
        }
87
88 1
        return true;
89
    }
90
91
92
    /**
93
     * @param array|Closure():array $data
94
     * @return $this
95
     */
96 25
    public function setDefaults(array|Closure $data): Form
97
    {
98
99 25
        if ($this->submitted === true) {
100 7
            $data = array_filter(
101 7
                match ($this->getMethod()) {
102 2
                    'GET' => $this->getRequest()->getQueryData()->toArray(),
103 5
                    'POST' => $this->getRequest()->getPostData()->toArray(),
104 7
                    default => [],
105
                },
106 7
                function ($k) {
107 7
                    return !in_array($k, [self::_TOKEN_CSRF_, self::_TOKEN_SUBMIT_]);
108
                },
109
                ARRAY_FILTER_USE_KEY
110
            );
111
        }
112
113 25
        if ($data instanceof Closure) {
0 ignored issues
show
introduced by
$data is never a sub-type of Closure.
Loading history...
114 2
            $data = $data();
115
            /** @psalm-suppress RedundantConditionGivenDocblockType */
116 2
            Assert::isArray($data);
117
        }
118
119 24
        $this->defaultsHandler->setData($data);
120 24
        return $this;
121
    }
122
123
124
    /**
125
     *
126
     * Если prepare() возвращает false, то элемент добавляется,
127
     * если true, то элемент добавлен в коллекцию не будет.
128
     * @use Element::setForm()
129
     * @use Element::prepare()
130
     * @param Element $element
131
     * @return $this
132
     */
133 86
    public function addElement(Element $element): self
134
    {
135 86
        $element->setForm($this);
136 86
        return $this->parentAddElement($element);
137
    }
138
139
140 86
    public function getDefaultsHandler(): DefaultsHandlerInterface
141
    {
142 86
        return $this->defaultsHandler;
143
    }
144
145 86
    public function getRequest(): ServerRequestWrapperInterface
146
    {
147 86
        return $this->request;
148
    }
149
150
    /**
151
     * @throws Exception\ExceptionRule
152
     */
153 86
    public function setMethod(string $method): void
154
    {
155 86
        if (in_array(strtoupper($method), self::_ALLOWED_FORM_METHOD_)) {
156 85
            $this->method = strtoupper($method);
157
        }
158 86
        $this->setAttribute(AttributeFactory::create('method', $this->method));
159 86
        $this->setOption('method', $this->method, false);
160 86
        $this->addElement(new Csrf($this->session));
161 86
        $this->setTokenSubmitElement();
162
    }
163
164 86
    public function getMethod(): string
165
    {
166 86
        return $this->method;
167
    }
168
169 86
    public function setAction(?string $action): self
170
    {
171 86
        $this->action = $action;
172 86
        $this->setAttribute(AttributeFactory::create('action', $this->action));
173 86
        $this->setOption('action', $this->action, false);
174 86
        $this->setTokenSubmitElement();
175 86
        return $this;
176
    }
177
178 5
    public function getAction(): ?string
179
    {
180 5
        return $this->action;
181
    }
182
183 86
    public function setId(?string $id): Form
184
    {
185 86
        $this->id = $id;
186 86
        $this->setAttribute(AttributeFactory::create('id', $this->id));
187 86
        $this->setOption('id', $this->id, false);
188 86
        $this->setTokenSubmitElement();
189 86
        return $this;
190
    }
191
192
193 2
    public function getId(): ?string
194
    {
195 2
        return $this->id;
196
    }
197
198 86
    private function setTokenSubmitElement(): void
199
    {
200
201 86
        $tokenSubmit = new TokenSubmit($this);
202 86
        $this->addElement($tokenSubmit->getElement());
203
204 86
        $this->submitted = $tokenSubmit->validate();
205
206
        // after every update the token submit, form needs check
207
        // and update defaults if form has been submitted.
208
        // Maybe in future will refactor this code
209 86
        if ($this->submitted === true) {
210 1
            $this->setDefaults([]);
211
        }
212
    }
213
214
//    /**
215
//     * Вывод формы в Renderer
216
//     * @param \Enjoys\Forms\Interfaces\RendererInterface $renderer
217
//     * @return mixed Возвращается любой формат, в зависимоти от renderer`а, может
218
//     * вернутся строка в html, или, например, xml или массив, все зависит от рендерера.
219
//     */
220
//    public function render(\Enjoys\Forms\Interfaces\RendererInterface $renderer): mixed
221
//    {
222
//        $renderer->setForm($this);
223
//        return $renderer->output();
224
//    }
225
}
226