Passed
Push — 5.x ( 811cbc...b9b3a2 )
by Enjoys
02:12
created

Form::setDefaults()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 14
c 4
b 0
f 0
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 9.7998
cc 3
nc 4
nop 1
crap 3
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 81
    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 81
        $this->request = $request ?? new ServerRequestWrapper(ServerRequestCreator::createFromGlobals());
62 81
        $this->session = $session ?? new Session();
63 81
        $this->defaultsHandler = $defaultsHandler ?? new DefaultsHandler();
64
65 81
        $this->setMethod($method);
66 81
        $this->setAction($action);
67 81
        $this->setId($id);
68
69 81
        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 22
    public function setDefaults(array|Closure $data): Form
100
    {
101
102 22
        if ($this->submitted === true) {
103 4
            $data = array_filter(
104 4
                match ($this->getMethod()) {
105 2
                    'GET' => $this->getRequest()->getQueryData()->toArray(),
106 2
                    'POST' => $this->getRequest()->getPostData()->toArray(),
107 4
                    default => [],
108
                },
109 4
                function ($k) {
110 4
                    return !in_array($k, [self::_TOKEN_CSRF_, self::_TOKEN_SUBMIT_]);
111
                },
112
                ARRAY_FILTER_USE_KEY
113
            );
114
        }
115
116 22
        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 2
            Assert::isArray($data);
119
        }
120
121 21
        $this->defaultsHandler->setData($data);
122 21
        return $this;
123
    }
124
125
126
    /**
127
     *
128
     * Если prepare() возвращает false, то элемент добавляется,
129
     * если true, то элемент добавлен в коллекцию не будет.
130
     * @use Element::setForm()
131
     * @use Element::prepare()
132
     * @param Element $element
133
     * @return $this
134
     */
135 81
    public function addElement(Element $element): self
136
    {
137 81
        $element->setForm($this);
138 81
        return $this->parentAddElement($element);
139
    }
140
141
142 81
    public function getDefaultsHandler(): DefaultsHandlerInterface
143
    {
144 81
        return $this->defaultsHandler;
145
    }
146
147 81
    public function getRequest(): ServerRequestWrapperInterface
148
    {
149 81
        return $this->request;
150
    }
151
152
    /**
153
     * @throws Exception\ExceptionRule
154
     */
155 81
    public function setMethod(string $method): void
156
    {
157 81
        if (in_array(strtoupper($method), self::_ALLOWED_FORM_METHOD_)) {
158 80
            $this->method = strtoupper($method);
159
        }
160 81
        $this->setAttribute(AttributeFactory::create('method', $this->method));
161 81
        $this->setOption('method', $this->method, false);
162 81
        $this->addElement(new Csrf($this->session));
163 81
        $this->setTokenSubmitElement();
164
    }
165
166 81
    public function getMethod(): string
167
    {
168 81
        return $this->method;
169
    }
170
171 81
    public function setAction(?string $action): self
172
    {
173 81
        $this->action = $action;
174 81
        $this->setAttribute(AttributeFactory::create('action', $this->action));
175 81
        $this->setOption('action', $this->action, false);
176 81
        $this->setTokenSubmitElement();
177 81
        return $this;
178
    }
179
180 5
    public function getAction(): ?string
181
    {
182 5
        return $this->action;
183
    }
184
185 81
    public function setId(?string $id): Form
186
    {
187 81
        $this->id = $id;
188 81
        $this->setAttribute(AttributeFactory::create('id', $this->id));
189 81
        $this->setOption('id', $this->id, false);
190 81
        $this->setTokenSubmitElement();
191 81
        return $this;
192
    }
193
194
195
    public function getId(): ?string
196
    {
197
        return $this->id;
198
    }
199
200 81
    private function setTokenSubmitElement(): void
201
    {
202 81
        $tokenSubmit = new TokenSubmit($this);
203 81
        $this->addElement($tokenSubmit->getElement());
204 81
        $this->submitted = $tokenSubmit->validate();
205
    }
206
207
//    /**
208
//     * Вывод формы в Renderer
209
//     * @param \Enjoys\Forms\Interfaces\RendererInterface $renderer
210
//     * @return mixed Возвращается любой формат, в зависимоти от renderer`а, может
211
//     * вернутся строка в html, или, например, xml или массив, все зависит от рендерера.
212
//     */
213
//    public function render(\Enjoys\Forms\Interfaces\RendererInterface $renderer): mixed
214
//    {
215
//        $renderer->setForm($this);
216
//        return $renderer->output();
217
//    }
218
}
219