Completed
Push — master ( 3830bc...2c9d17 )
by Samuel
02:31
created

Validator::getValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Kelemen\ApiNette\Validator;
4
5
use Kelemen\ApiNette\Exception\ValidatorException;
6
use Kelemen\ApiNette\Validator\Input\CookieInput;
7
use Kelemen\ApiNette\Validator\Input\FileInput;
8
use Kelemen\ApiNette\Validator\Input\GetInput;
9
use Kelemen\ApiNette\Validator\Input\InputInterface;
10
use Kelemen\ApiNette\Validator\Input\JsonInput;
11
use Kelemen\ApiNette\Validator\Input\PostInput;
12
use Kelemen\ApiNette\Validator\Input\PostRawInput;
13
use Nette\Utils\Validators;
14
15
class Validator implements ValidatorInterface
16
{
17
    /** @var array */
18
    private $validators = [];
19
20
    /** @var array */
21
    private $inputs = [];
22
23
    /** @var array */
24
    private $values = [];
25
26
    /** @var array */
27
    private $errors = [];
28
29
    /**
30
     * Configure validator
31
     */
32 24
    public function __construct()
33
    {
34 24
        $this->inputs = [
35 24
            'get' => new GetInput(),
36 24
            'post' => new PostInput(),
37 24
            'cookie' => new CookieInput(),
38 24
            'file' => new FileInput(),
39 24
            'postRaw' => new PostRawInput(),
40 24
            'json' => new JsonInput()
41 12
        ];
42 24
    }
43
44
    /**
45
     * Check if all validations are valid
46
     * @return bool
47
     */
48 16
    public function isValid()
49
    {
50 16
        return empty($this->errors);
51
    }
52
53
    /**
54
     * Get all validation errors
55
     * @return array
56
     */
57 12
    public function getErrors()
58
    {
59 12
        return $this->errors;
60
    }
61
62
    /**
63
     * @return array
64
     */
65 4
    public function getValues()
66
    {
67 4
        return $this->values;
68
    }
69
70
    /**
71
     * Set validator
72
     * @param string $name
73
     * @param callable $callback
74
     */
75 4
    public function setValidator($name, callable $callback)
76
    {
77 4
        $this->validators[$name] = $callback;
78 4
    }
79
80
    /**
81
     * Set input
82
     * @param string $name
83
     * @param InputInterface $input
84
     */
85 18
    public function setInput($name, InputInterface $input)
86
    {
87 18
        $this->inputs[$name] = $input;
88 18
    }
89
90
    /**
91
     * Validate given validators and store errors
92
     * @param array $validations
93
     * @throws ValidatorException
94
     */
95 18
    public function validate(array $validations)
96
    {
97 18
        $this->reset(); // For multiple use
98
99 18
        foreach ($validations as $validation) {
100 14
            if (!isset($this->inputs[$validation->getType()])) {
101 2
                throw new ValidatorException('Type ' . $validation->getType() . ' not registered');
102
            }
103
104 14
            $data = $this->inputs[$validation->getType()]->getData();
105 14
            $rules = explode('|', $validation->getRules());
106
107
            // Check if param is mandatory
108 14
            if (in_array('required', $rules)) {
109 10
                if (!isset($data[$validation->getKey()])) {
110 2
                    $this->errors[] = 'Validation for ' . $validation->getKey() . ' failed | required';
111 2
                    continue;
112
                }
113 8
                unset($rules[array_search('required', $rules)]);
114 4
            }
115
116
            // Check if optional param is set
117 14
            if (!isset($data[$validation->getKey()])) {
118 2
                continue;
119
            }
120
121 14
            $value = $data[$validation->getKey()];
122 14
            if ($this->validateRules($validation, $value, $rules)) {
123 11
                $this->values[$validation->getResultKey() ?: $validation->getKey()] = $value;
124 4
            }
125 9
        }
126 16
    }
127
128
    /**
129
     * Validate all validation rules for given value
130
     * @param Validation $validation
131
     * @param mixed $value
132
     * @param array $rules
133
     * @return bool
134
     */
135 14
    private function validateRules(Validation $validation, $value, array $rules)
136
    {
137 14
        $result = true;
138 14
        foreach ($rules as $rule) {
139 14
            list($type) = explode(':', $rule);
140
141 14
            if (!isset($this->validators[$type])) {
142 14
                $validateResult = Validators::is($value, $rule);
143 9
            } elseif (strpos($rule, ':') === false) {
144 4
                $validateResult = call_user_func($this->validators[$rule], $value);
145 2
            } else {
146 4
                list($type, $ruleParams) = explode(':', $rule, 2);
147 4
                $validateResult = call_user_func_array($this->validators[$type], [
148 4
                    'value' => $value,
149 2
                    'ruleParams' => $ruleParams
150 2
                ]);
151
            }
152
153 14
            if (!$validateResult) {
154 6
                $result = false;
155 10
                $this->errors[] = 'Validation for ' . $validation->getKey() . '(' . $value . ') failed | ' . $rule;
156 3
            }
157 7
        }
158
159 14
        return $result;
160
    }
161
162
    /**
163
     * Reset data
164
     */
165 18
    private function reset()
166
    {
167 18
        $this->errors = [];
168 18
        $this->values = [];
169 18
    }
170
}
171