Passed
Push — 5.x ( f7e86d...7f4590 )
by Enjoys
02:28
created

Form::setTokenSubmitElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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