Completed
Push — master ( ec446f...1d5331 )
by Peter
05:55
created

Validator   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 98.67%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 30
c 2
b 0
f 0
lcom 1
cbo 5
dl 0
loc 193
ccs 74
cts 75
cp 0.9867
rs 10

5 Methods

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