Passed
Push — master ( 439fe5...0de0cb )
by
unknown
01:42
created

Validation::run()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 0
Metric Value
dl 0
loc 23
c 0
b 0
f 0
cc 5
eloc 10
nc 8
nop 1
ccs 9
cts 10
cp 0.9
crap 5.025
rs 8.5906
1
<?php
2
3
namespace PluginSimpleValidate;
4
5
use PluginSimpleValidate\Libraries\Language;
6
7
class Validation implements \PluginSimpleValidate\Contracts\Validation
8
{
9
    /**
10
     * @var array
11
     * array of Field
12
     */
13
    private $fields;
14
15
    /**
16
     * @var array
17
     */
18
    private $errors;
19
20
    /**
21
     * @var Language
22
     */
23
    private $language;
24
25
    /**
26
     * @var bool
27
     */
28
    private $status;
29
30
    /**
31
     * Validation constructor.
32
     * @param Language $language
33
     */
34 1
    public function __construct(Language $language)
35
    {
36 1
        $this->language = $language;
37 1
        $this->fields = [];
38 1
        $this->errors = [];
39 1
        $this->status = false;
40 1
    }
41
42
    /**
43
     * @param \PluginSimpleValidate\Contracts\Field $field
44
     * @return $this
45
     */
46 1
    public function addField(\PluginSimpleValidate\Contracts\Field $field)
47
    {
48 1
        $this->fields[$field->getName()] = $field;
49 1
        return $this;
50
    }
51
52
    /**
53
     * @param bool $break_when_error
54
     * @return bool
55
     */
56 1
    public function run($break_when_error = false) : bool
57
    {
58
        /** @var Field $field */
59 1
        foreach ($this->fields as $field) {
60 1
            if (!$field->isValid($this->language)) {
61 1
                $this->status = false;
62 1
                $this->errors[$field->getName()] = $field->getErrors();
63
64
                /**
65
                 * break when there is any field error
66
                 */
67 1
                if ($break_when_error) {
68 1
                    break;
69
                }
70
            }
71
        }
72
73 1
        if (empty($this->errors)) {
74
            $this->status = true;
75
        }
76
77 1
        return $this->status;
78
    }
79
80
    /**
81
     * @return array
82
     */
83 1
    public function getErrors()
84
    {
85 1
        return $this->errors;
86
    }
87
88
    /**
89
     * @param string $fieldName
90
     * @return array|Field|null
91
     */
92
    public function getFields(string $fieldName = '')
93
    {
94
        if (empty($fieldName)) {
95
            return $this->fields;
96
        }
97
98
        return isset($this->fields[$fieldName]) ? $this->fields[$fieldName] : null;
99
    }
100
101
    /**
102
     * @return bool
103
     */
104
    public function getStatus(): bool
105
    {
106
        return $this->status;
107
    }
108
}