FormField::dataValid()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 7.1428
c 0
b 0
f 0
cc 8
eloc 13
nc 11
nop 0
1
<?php
2
3
namespace hemio\form\Abstract_;
4
5
/**
6
 * Field in a form that expects inputs maybe composed of several input elements.
7
 */
8
abstract class FormField extends FormElement
9
{
10
    /**
11
     *
12
     * @var boolean
13
     */
14
    protected $required = false;
15
16
    /**
17
     *
18
     * @var array[string]
19
     */
20
    protected $errors = [];
21
22
    /**
23
     *
24
     * @return array[string]
0 ignored issues
show
Documentation introduced by
The doc-type array[string] could not be parsed: Expected "]" at position 2, but found "string". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
25
     */
26
    public function getErrors()
27
    {
28
        return $this->errors;
29
    }
30
31
    /**
32
     *
33
     */
34
    public function dataValid()
35
    {
36
        if (!strlen($this->getValueUser()) && !$this->required) {
37
            // don't apply checks, if empty and not required
38
            return true;
39
        } else {
40
            $allValid = true;
41
42
            foreach ($this->checks as $key => $check) {
43
                $valid          = $check($this->getValueUser());
44
                $allValid       = $allValid && $valid;
45
                if (!$valid)
46
                    $this->errors[] = $check->getMessage();
47
            }
48
49
            if (!$allValid && $this instanceof \hemio\form\Focusable)
50
                $this->setAutofocus(true, 20);
51
52
            return $allValid;
53
        }
54
    }
55
    /**
56
     *
57
     * @var array[Check]
58
     */
59
    public $checks = [];
60
61
    /**
62
     *
63
     * @param Check $check
64
     */
65
    public function addValidityCheck(\hemio\form\Check $check)
66
    {
67
        $this->checks[$check->getId()] = $check;
68
    }
69
}
70