Completed
Push — master ( 507c4a...51e00b )
by Peter
07:40
created

Validator   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 98.72%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 31
lcom 1
cbo 5
dl 0
loc 200
ccs 77
cts 78
cp 0.9872
rs 9.8
c 2
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
D validate() 0 84 14
A getErrors() 0 4 1
C validateEntity() 0 61 12
A setErrors() 0 7 2
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 136
	public function __construct(AnnotatedInterface $model)
50
	{
51 136
		$this->model = $model;
52 136
		$this->meta = ManganMeta::create($this->model);
53
54
		// Ensure that errors array is initialized - even if does not have validators
55 136
		foreach (array_keys($this->meta->fields()) as $name)
56
		{
57 136
			$this->errors[$name] = [];
58
		}
59 136
	}
60
61
	/**
62
	 * Validate model, optionally only selected fields
63
	 * @param string[] $fields
64
	 * @return boolean
65
	 */
66 100
	public function validate($fields = [])
67
	{
68 100
		$valid = [];
69 100
		if (empty($fields))
70
		{
71 100
			$fields = array_keys($this->meta->fields());
72
		}
73 100
		foreach ($fields as $name)
74
		{
75 100
			$fieldMeta = $this->meta->field($name);
76
77
			// Reset errors
78 100
			$this->errors[$name] = [];
79
80
			// Check if meta for field exists
81 100
			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 100
			if ($fieldMeta->owned && $fieldMeta->updatable)
89
			{
90 25
				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 18
				} elseif (!empty($this->model->$name))
109
				{
110
					// Handle single documents
111 17
					$validator = new Validator($this->model->$name);
112 17
					$isValid = $validator->validate();
113 17
					$valid[] = (int)$isValid;
114 17
					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 100
			if (empty($fieldMeta->validators))
126
			{
127 99
				continue;
128
			}
129 21
			$valid[] = (int)$this->validateEntity($name, $fieldMeta->validators);
130
		}
131
132
		// Model validators
133 100
		$typeValidators = $this->meta->type()->validators;
134 100
		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 100
		$areAllValid = count($valid) === array_sum($valid);
142
143
		// For easier debug
144 100
		if($areAllValid)
145
		{
146 97
			return true;
147
		}
148 22
		return false;
149
	}
150
151 22
	private function validateEntity($name, $validators)
152
	{
153 22
		$valid = [];
154 22
		foreach ($validators as $validatorMeta)
155
		{
156
			// Filter out validators based on scenarios
157 22
			if (!empty($validatorMeta->on))
158
			{
159 2
				$on = (array)$validatorMeta->on;
160 2
				$enabled = false;
161 2
				foreach ($on as $scenario)
162
				{
163 2
					if ($scenario === ScenarioManager::getScenario($this->model))
164
					{
165 2
						$enabled = true;
166 2
						break;
167
					}
168
				}
169 2
				if (!$enabled)
170
				{
171 2
					continue;
172
				}
173
			}
174 22
			if (!empty($validatorMeta->except))
175
			{
176 1
				$except = (array)$validatorMeta->except;
177 1
				$enabled = true;
178 1
				foreach ($except as $scenario)
179
				{
180 1
					if ($scenario === ScenarioManager::getScenario($this->model))
181
					{
182 1
						$enabled = false;
183 1
						break;
184
					}
185
				}
186 1
				if (!$enabled)
187
				{
188 1
					continue;
189
				}
190
			}
191
192
193
			// Create validator and validate
194 22
			$validator = Factory::create($this->model, $validatorMeta, $name);
195 22
			if ($validator->isValid($this->model, $name))
196
			{
197 18
				$valid[] = true;
198
			} else
199
			{
200 22
				$valid[] = false;
201 22
				$this->errors[$name] = array_merge($this->errors[$name], $validator->getErrors());
202
203
				// Set errors to model instance if it implements ValidatableInterface
204 22
				if ($this->model instanceof ValidatableInterface)
205
				{
206 22
					$this->model->setErrors($this->errors);
207
				}
208
			}
209
		}
210 22
		return count($valid) === array_sum($valid);
211
	}
212
213 10
	public function getErrors()
214
	{
215 10
		return $this->errors;
216
	}
217
218 12
	public function setErrors($errors)
219
	{
220 12
		foreach ($errors as $field => $errors)
221
		{
222 12
			$this->errors[$field] = $errors;
223
		}
224 12
	}
225
226
}
227