Completed
Push — master ( 2bd557...c77e24 )
by Shcherbak
34:56 queued 32:47
created

Form::setData()   D

Complexity

Conditions 9
Paths 24

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9.0945

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 32
ccs 17
cts 19
cp 0.8947
rs 4.909
cc 9
eloc 18
nc 24
nop 1
crap 9.0945
1
<?php
2
3
4
  namespace Fiv\Form;
5
6
  use Fiv\Form\Element;
7
  use Fiv\Form\Element\Checkbox;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Fiv\Form\Checkbox.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
  use Fiv\Form\Element\CheckboxList;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Fiv\Form\CheckboxList.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
  use Fiv\Form\Element\Submit;
10
  use Fiv\Form\Element\TextArea;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Fiv\Form\TextArea.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
11
12
  /**
13
   * @author Ivan Shcherbak <[email protected]>
14
   */
15
  class Form extends Element\Html {
16
17
    /**
18
     * @var null|string
19
     */
20
    protected $uid = null;
21
22
    /**
23
     * @var boolean|null
24
     */
25
    protected $validationResult = null;
26
27
    /**
28
     * @var array|null
29
     */
30
    protected $data = null;
31
32
    /**
33
     * @var bool
34
     */
35
    protected $isSubmitted = false;
36
37
    /**
38
     * @var Element\BaseElement[]
39
     */
40
    protected $elements = [];
41
42
    /**
43
     * Default form attributes
44
     *
45
     * @var array
46
     */
47
    protected $attributes = [
48
      'method' => 'post',
49
    ];
50
51
52
    /**
53
     * @param $name
54
     * @return $this
55
     */
56 8
    public function setName($name) {
57 8
      $this->uid = $name;
58 8
      $this->attributes['name'] = $name;
59 8
      return $this;
60
    }
61
62
63
    /**
64
     * @return array
65
     * @throws \Exception
66
     */
67 1
    public function getData() {
68 1
      if (!isset($this->data)) {
69
        throw new \Exception("Data does not exist!");
70
      }
71
72 1
      return $this->data;
73
    }
74
75
76
    /**
77
     * @param array|\Iterator $data
78
     * @throws \Exception
79
     */
80 14
    public function setData($data) {
81 14
      if ($data instanceof \Iterator) {
82
        $data = iterator_to_array($data);
83
      }
84
85 14
      if (!is_array($data)) {
86 1
        throw new \Exception('Data should be an array');
87
      }
88
89
90 13
      $this->cleanValidationFlag();
91
92 13
      $formData = [];
93 13
      foreach ($this->elements as $element) {
94 12
        $name = $element->getName();
95
96 12
        if ($element instanceof Checkbox) {
97 2
          $data[$name] = array_key_exists($name, $data) ? 1 : 0;
98 10
        } elseif ($element instanceof CheckboxList) {
99
          $data[$name] = isset($data[$name]) ? $data[$name] : [];
100
        }
101
102 12
        if (array_key_exists($name, $data)) {
103 11
          $element->setValue($data[$name]);
104 12
          $formData[$name] = $element->getValue();
105
        }
106
107
      }
108
109 13
      $this->isSubmitted = isset($data[$this->getUid()]);
110 13
      $this->data = $formData;
111 13
    }
112
113
114
    /**
115
     * @return string
116
     */
117 4
    public function getMethod() {
118 4
      if (!empty($this->attributes['method'])) {
119 4
        return strtolower($this->attributes['method']);
120
      }
121
122 1
      return null;
123
    }
124
125
126
    /**
127
     * @param string $method
128
     * @return $this
129
     */
130 2
    public function setMethod($method) {
131 2
      $this->attributes['method'] = $method;
132
133 2
      return $this;
134
    }
135
136
137
    /**
138
     *
139
     */
140 22
    protected function cleanValidationFlag() {
141 22
      $this->validationResult = null;
142 22
    }
143
144
145
    /**
146
     * Check if form is submitted and all elements are valid
147
     *
148
     * @return boolean
149
     */
150 9
    public function isValid() {
151 9
      if ($this->validationResult !== null) {
152 1
        return $this->validationResult;
153
      }
154
155 9
      if (!$this->isSubmitted()) {
156 2
        return false;
157
      }
158
159 8
      $this->validationResult = true;
160 8
      foreach ($this->elements as $element) {
161 8
        if (!$element->isValid()) {
162 8
          $this->validationResult = false;
163
        }
164
      }
165
166 8
      return $this->validationResult;
167
    }
168
169
170
    /**
171
     * Check if form is submitted
172
     *
173
     * @return bool
174
     */
175 11
    public function isSubmitted() {
176 11
      return $this->isSubmitted;
177
    }
178
179
180
    /**
181
     * Return unique id of form
182
     *
183
     * @return string
184
     */
185 17
    public function getUid() {
186 17
      if (empty($this->uid)) {
187 13
        $this->uid = md5(get_called_class());
188
      }
189
190 17
      return $this->uid;
191
    }
192
193
194
    /**
195
     * @return Element\BaseElement[]
196
     */
197 4
    public function getElements() {
198 4
      return $this->elements;
199
    }
200
201
202
    /**
203
     * @param string $name
204
     * @param string|null $text
205
     * @return \Fiv\Form\Element\Input
206
     */
207 8
    public function input($name, $text = null) {
208 8
      $input = new Element\Input();
209 8
      $input->setName($name);
210 8
      $input->setText($text);
211 8
      $this->addElement($input);
212 8
      return $input;
213
    }
214
215
216
    /**
217
     * @param string $name
218
     * @param string|null $text
219
     * @return \Fiv\Form\Element\Input
220
     */
221
    public function password($name, $text = null) {
222
      $input = new Element\Password();
223
      $input->setName($name);
224
      $input->setText($text);
225
      $this->addElement($input);
226
      return $input;
227
    }
228
229
230
    /**
231
     * @param string $name
232
     * @param null $text
233
     * @return Select
234
     */
235
    public function select($name, $text = null) {
236
      $select = new Element\Select();
237
      $select->setName($name);
238
      $select->setText($text);
239
      $this->addElement($select);
240
      return $select;
241
    }
242
243
244
    /**
245
     * @param string $name
246
     * @param string $text
247
     * @return RadioList
248
     */
249
    public function radioList($name, $text = null) {
250
      $radio = new Element\RadioList();
251
      $radio->setName($name);
252
      $radio->setText($text);
253
      $this->addElement($radio);
254
      return $radio;
255
    }
256
257
258
    /**
259
     * @param string $name
260
     * @param null $text
261
     * @return TextArea
262
     */
263 4
    public function textarea($name, $text = null) {
264 4
      $input = new TextArea();
265 4
      $input->setName($name);
266 4
      $input->setText($text);
267 4
      $this->addElement($input);
268 4
      return $input;
269
    }
270
271
272
    /**
273
     * ```
274
     * $form->hidden('key', md5($this-user->id . HASH_A);
275
     * ```
276
     * @param string $name
277
     * @param null $value
278
     * @return \Fiv\Form\Element\Input
279
     */
280 3
    public function hidden($name, $value = null) {
281 3
      $hidden = new  \Fiv\Form\Element\Input();
282 3
      $hidden->setType('hidden');
283 3
      $hidden->setName($name);
284 3
      $hidden->setValue($value);
285 3
      $this->addElement($hidden);
286 3
      return $hidden;
287
    }
288
289
290
    /**
291
     * ```
292
     * $form->submit('register', 'зареєструватись');
293
     * ```
294
     * @param string $name
295
     * @param null $value
296
     * @return Submit
297
     */
298 1
    public function submit($name, $value = null) {
299 1
      $input = new Submit();
300 1
      $input->setName($name);
301 1
      $input->setValue($value);
302 1
      $this->addElement($input);
303 1
      return $input;
304
    }
305
306
307
    /**
308
     * ```
309
     * $form->checkbox('subscribe', 'Підписка на новини');
310
     * ```
311
     * @param string $name
312
     * @param string|null $label
313
     * @return Checkbox
314
     */
315 2
    public function checkbox($name, $label = null) {
316 2
      $checkbox = new Checkbox();
317 2
      $checkbox->setName($name);
318 2
      $checkbox->setLabel($label);
319 2
      $this->addElement($checkbox);
320 2
      return $checkbox;
321
    }
322
323
324
    /**
325
     * @param string $name
326
     * @param null $text
327
     * @return CheckboxList
328
     */
329
    public function checkboxList($name, $text = null) {
330
      $checkbox = new CheckboxList();
331
      $checkbox->setName($name);
332
      $checkbox->setText($text);
333
      $this->addElement($checkbox);
334
      return $checkbox;
335
    }
336
337
338
    /**
339
     * Attach element to this form. Overwrite element with same name
340
     *
341
     * @param Element\BaseElement $element
342
     * @return $this
343
     */
344 2
    public function setElement(Element\BaseElement $element) {
345 2
      $this->cleanValidationFlag();
346 2
      $this->elements[$element->getName()] = $element;
347 2
      return $this;
348
    }
349
350
351
    /**
352
     * @param Element\BaseElement $element
353
     * @return $this
354
     * @throws \Exception
355
     */
356 19
    public function addElement(Element\BaseElement $element) {
357 19
      if (isset($this->elements[$element->getName()])) {
358 1
        throw new \Exception('Element with name ' . $element->getName() . ' is already added. Use setElement to overwrite it or change name');
359
      }
360
361 19
      $this->cleanValidationFlag();
362 19
      $this->elements[$element->getName()] = $element;
363 19
      return $this;
364
    }
365
366
367
    /**
368
     * Render full form
369
     *
370
     * @return string
371
     */
372 2
    public function render() {
373 2
      return $this->renderStart() . $this->renderElements() . $this->renderEnd();
374
    }
375
376
377
    /**
378
     * You can easy rewrite this method for custom design of your forms
379
     *
380
     * @return string
381
     */
382 2
    protected function renderElements() {
383 2
      $formHtml = '<dl>';
384
385 2
      foreach ($this->elements as $element) {
386
        # skip hidden element
387 1
        if ($element instanceof Element\Input and $element->getType() === 'hidden') {
388
          continue;
389
        }
390
391
        $formHtml .=
392 1
          '<dt>' . $element->getText() . '</dt>' .
393 1
          '<dd>' . $element->render() . '</dd>';
394
      }
395
396 2
      $formHtml .= '</dl>';
397 2
      return $formHtml;
398
    }
399
400
401
    /**
402
     * @return string
403
     */
404 3
    public function renderStart() {
405 3
      $hidden = new Element\Input();
406 3
      $hidden->setType('hidden');
407 3
      $hidden->addAttributes([
408 3
        'name' => $this->getUid(),
409
      ]);
410 3
      $hidden->setValue(1);
411
412
413
      # get default attribute
414 3
      $method = $this->getMethod();
415 3
      $this->setAttribute('method', $method);
416
417 3
      $html = '<form ' . $this->getAttributesAsString() . '>';
418 3
      $html .= $hidden->render();
419
420
      # render hidden element
421 3
      foreach ($this->elements as $element) {
422 2
        if ($element instanceof Element\Input and $element->getType() === 'hidden') {
423 2
          $html .= $element->render();
424
        }
425
      }
426
427
428 3
      return $html;
429
    }
430
431
432
    /**
433
     * @return string
434
     */
435 3
    public function renderEnd() {
436 3
      return '</form>';
437
    }
438
439
  }