Completed
Push — master ( fa66ff...b613b3 )
by Peter
10:20
created

Validator::validate()   D

Complexity

Conditions 14
Paths 90

Size

Total Lines 84
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 14.0038

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 84
ccs 36
cts 37
cp 0.973
rs 4.9516
c 2
b 0
f 0
cc 14
eloc 40
nc 90
nop 1
crap 14.0038

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This software package is licensed under AGPL or Commercial license.
5
 *
6
 * @package maslosoft/mangan
7
 * @licence AGPL or Commercial
8
 * @copyright Copyright (c) Piotr Masełkowski <[email protected]>
9
 * @copyright Copyright (c) Maslosoft
10
 * @copyright Copyright (c) Others as mentioned in code
11
 * @link https://maslosoft.com/mangan/
12
 */
13
14
namespace Maslosoft\Mangan;
15
16
use InvalidArgumentException;
17
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
18
use Maslosoft\Mangan\Helpers\Validator\Factory;
19
use Maslosoft\Mangan\Interfaces\ValidatableInterface;
20
use Maslosoft\Mangan\Meta\ManganMeta;
21
22
/**
23
 * Validator
24
 *
25
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
26
 */
27
class Validator implements ValidatableInterface
28
{
29
30
	/**
31
	 * Model instance
32
	 * @var AnnotatedInterface
33
	 */
34
	private $model = null;
35
36
	/**
37
	 * Metadata for model
38
	 * @var ManganMeta
39
	 */
40
	private $meta = null;
41
42
	/**
43
	 * Array of error messages.
44
	 * Keys are field names, secondary keys are numeric
45
	 * @var string[][]
46
	 */
47
	private $errors = [];
48
49 128
	public function __construct(AnnotatedInterface $model)
50
	{
51 128
		$this->model = $model;
52 128
		$this->meta = ManganMeta::create($this->model);
53
54
		// Ensure that errors array is initialized - even if does not have validators
55 128
		foreach (array_keys($this->meta->fields()) as $name)
56
		{
57 128
			$this->errors[$name] = [];
58
		}
59 128
	}
60
61
	/**
62
	 * Validate model, optionally only selected fields
63
	 * @param string[] $fields
64
	 * @return boolean
65
	 */
66 92
	public function validate($fields = [])
67
	{
68 92
		$valid = [];
69 92
		if (empty($fields))
70
		{
71 92
			$fields = array_keys($this->meta->fields());
72
		}
73 92
		foreach ($fields as $name)
74
		{
75 92
			$fieldMeta = $this->meta->field($name);
76
77
			// Reset errors
78 92
			$this->errors[$name] = [];
79
80
			// Check if meta for field exists
81 92
			if (empty($fieldMeta))
82
			{
83
				throw new InvalidArgumentException(sprintf("Unknown field `%s` in model `%s`", $name, get_class($this->model)));
84
			}
85
86
			// Validate sub documents
87
			// Skip fields that are not updatable
88 92
			if ($fieldMeta->owned && $fieldMeta->updatable)
89
			{
90 28
				if (is_array($this->model->$name))
91
				{
92
					// Handle arrays of documents
93 11
					foreach ($this->model->$name as $fieldIndex => $model)
94
					{
95 11
						$validator = new Validator($model);
96 11
						$isValid = $validator->validate();
97 11
						$valid[] = (int)$isValid;
98 11
						if (!$isValid)
99
						{
100
							$errors = [
101
								$name => [
102 3
									$fieldIndex => $validator->getErrors()
103
								]
104
							];
105 11
							$this->setErrors($errors);
106
						}
107
					}
108 21
				} elseif (!empty($this->model->$name))
109
				{
110
					// Handle single documents
111 20
					$validator = new Validator($this->model->$name);
112 20
					$isValid = $validator->validate();
113 20
					$valid[] = (int)$isValid;
114 20
					if (!$isValid)
115
					{
116
						$errors = [
117 3
							$name => $validator->getErrors()
118
						];
119 3
						$this->setErrors($errors);
120
					}
121
				}
122
			}
123
124
			// Skip field without validators
125 92
			if (empty($fieldMeta->validators))
126
			{
127 91
				continue;
128
			}
129 21
			$valid[] = (int)$this->validateEntity($name, $fieldMeta->validators);
130
		}
131
132
		// Model validators
133 92
		$typeValidators = $this->meta->type()->validators;
134 92
		if (!empty($typeValidators))
135
		{
136 1
			$typeName = $this->meta->type()->name;
137
			// Reset errors
138 1
			$this->errors[$typeName] = [];
139 1
			$valid[] = (int)$this->validateEntity($typeName, $typeValidators);
140
		}
141 92
		$areAllValid = count($valid) === array_sum($valid);
142
143
		// For easier debug
144 22
		if($areAllValid)
145
		{
146 22
			return true;
147 22
		}
148
		return false;
149
	}
150 22
151
	private function validateEntity($name, $validators)
152 2
	{
153 2
		$valid = [];
154 2
		foreach ($validators as $validatorMeta)
155
		{
156 2
			// Filter out validators based on scenarios
157
			if (!empty($validatorMeta->on))
158 2
			{
159 2
				$on = (array)$validatorMeta->on;
160
				$enabled = false;
161
				foreach ($on as $scenario)
162 2
				{
163
					if ($scenario === ScenarioManager::getScenario($this->model))
164 2
					{
165
						$enabled = true;
166
						break;
167 22
					}
168
				}
169 1
				if (!$enabled)
170 1
				{
171 1
					continue;
172
				}
173 1
			}
174
			if (!empty($validatorMeta->except))
175 1
			{
176 1
				$except = (array)$validatorMeta->except;
177
				$enabled = true;
178
				foreach ($except as $scenario)
179 1
				{
180
					if ($scenario === ScenarioManager::getScenario($this->model))
181 1
					{
182
						$enabled = false;
183
						break;
184
					}
185
				}
186
				if (!$enabled)
187 22
				{
188 22
					continue;
189
				}
190 18
			}
191
192
193 22
			// Create validator and validate
194 22
			$validator = Factory::create($this->model, $validatorMeta, $name);
195
			if ($validator->isValid($this->model, $name))
196
			{
197 22
				$valid[] = true;
198
			} else
199 22
			{
200
				$valid[] = false;
201
				$this->errors[$name] = array_merge($this->errors[$name], $validator->getErrors());
202
203 22
				// Set errors to model instance if it implements ValidatableInterface
204
				if ($this->model instanceof ValidatableInterface)
205
				{
206 9
					$this->model->setErrors($this->errors);
207
				}
208 9
			}
209
		}
210
		return count($valid) === array_sum($valid);
211 12
	}
212
213 12
	public function getErrors()
214
	{
215 12
		return $this->errors;
216
	}
217 12
218
	public function setErrors($errors)
219
	{
220
		foreach ($errors as $field => $errors)
221
		{
222
			$this->errors[$field] = $errors;
223
		}
224
	}
225
226
}
227