Passed
Push — master ( 34f20f...a12a6d )
by Enjoys
57s queued 12s
created

Form::setTokenSubmitElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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