Completed
Pull Request — master (#28)
by Vitaliy
02:51
created

Form::addElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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