Validator::checkType()   C
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 22
nc 7
nop 2
1
<?php
2
3
namespace HelePartnerSyncApi;
4
5
use DateTime;
6
use DateTimeInterface;
7
8
class Validator
9
{
10
11
	const TYPE_NULL = 'null';
12
	const TYPE_ARRAY = 'array';
13
	const TYPE_INT = 'int';
14
	const TYPE_STRING = 'string';
15
	const TYPE_DATE_TIME = 'datetime';
16
	const TYPE_DATE_TIME_STRING = 'datetimestring';
17
18
	/**
19
	 * @param mixed $value
20
	 * @param string $type self::TYPE_*
21
	 */
22
	public static function checkType($value, $type)
23
	{
24
		switch ($type) {
25
			case self::TYPE_NULL:
26
				self::checkNull($value);
27
				break;
28
29
			case self::TYPE_ARRAY:
30
				self::checkArray($value);
31
				break;
32
33
			case self::TYPE_INT:
34
				self::checkInt($value);
35
				break;
36
37
			case self::TYPE_STRING:
38
				self::checkString($value);
39
				break;
40
41
			case self::TYPE_DATE_TIME:
42
				self::checkDateTime($value);
43
				break;
44
45
			case self::TYPE_DATE_TIME_STRING:
46
				self::checkDateTimeString($value);
47
				break;
48
49
			default:
50
				throw new ValidatorException(sprintf('Unknown type %s to validate', is_scalar($type) ? $type : self::getType($type)));
51
		}
52
	}
53
54
	public static function checkStructure($data, array $structure, array $path = array())
55
	{
56
		if (count($structure) === 0) {
57
			throw new ValidatorException(sprintf('Cannot validate against empty structure in %s', self::getStructurePath($path)));
58
		}
59
60
		self::checkArray($data);
61
		self::checkArray($structure);
62
63
		$listCheck = self::isList($structure);
64
		if (!$listCheck) {
65 View Code Duplication
			if (count($data) > 0 && self::isList($data)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
				throw new ValidatorException(sprintf('Unexpected list structure (%s elements found) in %s', count($data), self::getStructurePath($path)));
67
			}
68
69
			$diff = array_diff_key($data, $structure);
70 View Code Duplication
			if (count($diff) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
				throw new ValidatorException(sprintf('Unknown keys (%s) in %s', implode(', ', array_keys($diff)), self::getStructurePath($path)));
72
			}
73
74
			$diff = array_diff_key($structure, $data);
75 View Code Duplication
			if (count($diff) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
				throw new ValidatorException(sprintf('Missing keys (%s) in %s', implode(', ', array_keys($diff)), self::getStructurePath($path)));
77
			}
78
79 View Code Duplication
		} elseif (count($data) > 0 && !self::isList($data)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
			throw new ValidatorException(sprintf('Expected list structure in %s', self::getStructurePath($path)));
81
		}
82
83
		foreach ($data as $key => $value) {
84
			try {
85
				$newStructure = $listCheck ? $structure[0] : $structure[$key];
86
87
				if (is_array($newStructure)) {
88
					$newPath = array_merge($path, array($key));
89
					self::checkArray($value);
90
					self::checkStructure($value, $newStructure, $newPath);
91
				} else {
92
					self::checkType($value, $newStructure);
93
				}
94
95
			} catch (ValidatorException $e) {
96
				throw new ValidatorException(sprintf('Invalid type in %s: %s', self::getStructurePath($path, $key), $e->getMessage()), $e);
97
			}
98
		}
99
	}
100
101
	/**
102
	 * @param mixed $value
103
	 */
104
	public static function checkNull($value)
105
	{
106
		if (!is_null($value)) {
107
			self::throwException('Null', $value);
108
		}
109
	}
110
111
	/**
112
	 * @param mixed $value
113
	 */
114
	public static function checkArray($value)
115
	{
116
		if (!is_array($value)) {
117
			self::throwException('Array', $value);
118
		}
119
	}
120
121
	/**
122
	 * @param mixed $value
123
	 */
124
	public static function checkDateTime($value)
125
	{
126
		if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
1 ignored issue
show
Bug introduced by
The class DateTimeInterface does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
127
			self::throwException('DateTime', $value);
128
		}
129
	}
130
131
	/**
132
	 * @param mixed $value
133
	 */
134
	public static function checkDateTimeString($value)
135
	{
136
		self::checkString($value);
137
138
		$dateTime = DateTime::createFromFormat(DateTime::W3C, $value);
139
		if ($dateTime === false) {
140
			self::throwException('W3C datetime', $value);
141
		}
142
	}
143
144
	/**
145
	 * @param mixed $value
146
	 */
147
	public static function checkInt($value)
148
	{
149
		if (!is_int($value)) {
150
			self::throwException('Int', $value);
151
		}
152
	}
153
154
	/**
155
	 * @param mixed $value
156
	 */
157
	public static function checkString($value)
158
	{
159
		if (!is_string($value)) {
160
			self::throwException('String', $value);
161
		}
162
	}
163
164
	/**
165
	 * @param string $type
166
	 * @param mixed $value
167
	 * @internal
168
	 */
169
	private static function throwException($type, $value)
170
	{
171
		if (is_scalar($value)) {
172
			throw new ValidatorException(sprintf('%s expected, %s (%s) given.', $type, self::getType($value), $value));
173
		} else {
174
			throw new ValidatorException(sprintf('%s expected, %s given.', $type, self::getType($value)));
175
		}
176
	}
177
178
	/**
179
	 * @param mixed $value
180
	 * @return string
181
	 */
182
	private static function getType($value)
183
	{
184
		return is_object($value) ? get_class($value) : gettype($value);
185
	}
186
187
	/**
188
	 * @param mixed $value
189
	 * @return bool
190
	 */
191
	private static function isList($value)
192
	{
193
		return is_array($value) && (count($value) === 0 || array_keys($value) === range(0, count($value) - 1));
194
	}
195
196
	/**
197
	 * @param array $path
198
	 * @param string|null $currentKey
199
	 * @return string
200
	 */
201
	private static function getStructurePath(array $path, $currentKey = null)
202
	{
203
		if ($currentKey !== null) {
204
			$path[] = $currentKey;
205
		}
206
207
		if (count($path) === 0) {
208
			return 'root';
209
		} elseif (count($path) === 1) {
210
			return sprintf('key \'%s\'', $path[0]);
211
		} else {
212
			return sprintf('path \'%s\'', implode('.', $path));
213
		}
214
	}
215
216
}
217