Completed
Push — v2 ( 604284...1c0690 )
by Berend
02:58
created

AutoApi::validateInputValues()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8.3518

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 29
c 0
b 0
f 0
ccs 14
cts 17
cp 0.8235
rs 8.4444
cc 8
nc 10
nop 1
crap 8.3518
1
<?php
2
3
namespace miBadger\ActiveRecord\Traits;
4
5
use miBadger\ActiveRecord\ColumnProperty;
6
use miBadger\ActiveRecord\ActiveRecordException;
7
use miBadger\Query\Query;
8
9
trait AutoApi
10
{
11
	/* =======================================================================
12
	 * ===================== Automatic API Support ===========================
13
	 * ======================================================================= */
14
15
	/** @var array A map of column name to functions that hook the insert function */
16
	protected $registeredCreateHooks;
17
18
	/** @var array A map of column name to functions that hook the read function */
19
	protected $registeredReadHooks;
20
21
	/** @var array A map of column name to functions that hook the update function */
22
	protected $registeredUpdateHooks;
23
24
	/** @var array A map of column name to functions that hook the update function */
25
	protected $registeredDeleteHooks;	
26
27
	/** @var array A map of column name to functions that hook the search function */
28
	protected $registeredSearchHooks;
29
30
	/** @var array A list of table column definitions */
31
	protected $tableDefinition;
32
33 1
	public function apiSearch(Array $queryparams, Array $fieldWhitelist)
34
	{
35
		// @TODO: Would it be better to not include the ignored_traits?
36 1
		$ignoredTraits = $queryparams['ignored_traits'] ?? [];
37 1
		$query = $this->search($ignoredTraits);
0 ignored issues
show
Bug introduced by
It seems like search() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
		/** @scrutinizer ignore-call */ 
38
  $query = $this->search($ignoredTraits);
Loading history...
38
39 1
		$orderColumn = $queryparams['order_by'] ?? null;
40 1
		$orderDirection = $queryparams['order_direction'] ?? null;
41 1
		if ($orderColumn !== null) {
42 1
			$query->orderBy($orderColumn, $orderDirection);
43
		}
44
		
45 1
		$limit = $queryparams['limit'] ?? null;
46 1
		if ($limit !== null) {
47
			$query->limit($limit);
48
		}
49
50 1
		$offset = $queryparams['offset'] ?? null;
51 1
		if ($offset !== null) {
52
			$query->offset($offset);
53
		}
54
55 1
		$results = $query->fetchAll();
56
57 1
		$resultsArray = [];
58 1
		foreach ($results as $result) {
59 1
			$resultsArray[] = $result->toArray($fieldWhitelist);
60
		}
61
62 1
		return $resultsArray;
63
	}
64
65 5
	public function toArray($fieldWhitelist)
66
	{
67 5
		$output = [];
68 5
		foreach ($this->tableDefinition as $colName => $definition) {
69 5
			if (in_array($colName, $fieldWhitelist)) {
70 5
				$output[$colName] = $definition['value'];
71
			}
72
		}
73
74 5
		return $output;
75
	}
76
77 1
	public function apiRead($id, Array $fieldWhitelist)
78
	{
79 1
		$this->read($id);
80 1
		return $this->toArray($fieldWhitelist);
81
	}
82
83
	/* =============================================================
84
	 * ===================== Constraint validation =================
85
	 * ============================================================= */
86
87
	/**
88
	 * Copy all table variables between two instances
89
	 */
90 3
	private function syncInstances($to, $from)
91
	{
92 3
		foreach ($to->tableDefinition as $colName => $definition) {
93 3
			$definition['value'] = $from->tableDefinition[$colName]['value'];
94
		}
95 3
	}
96
97 9
	private function filterInputColumns($input, $whitelist)
98
	{
99 9
		$filteredInput = $input;
100 9
		foreach ($input as $colName => $value) {
101 9
			if (!in_array($colName, $whitelist)) {
102 9
				unset($filteredInput[$colName]);
103
			}
104
		}
105 9
		return $filteredInput;
106
	}
107
108 9
	private function validateExcessKeys($input)
109
	{
110 9
		$errors = [];
111 9
		foreach ($input as $colName => $value) {
112 9
			if (!array_key_exists($colName, $this->tableDefinition)) {
113 1
				$errors[$colName] = "Unknown input field";
114 9
				continue;
115
			}
116
		}
117 9
		return $errors;
118
	}
119
120 4
	private function validateImmutableColumns($input)
121
	{
122 4
		$errors = [];
123 4
		foreach ($this->tableDefinition as $colName => $definition) {
124 4
			$property = $definition['properties'] ?? null;
125 4
			if (array_key_exists($colName, $input)
126 4
				&& $property & ColumnProperty::IMMUTABLE) {
127 4
				$errors[$colName] = "Field cannot be changed";
128
			}
129
		}
130 4
		return $errors;
131
	}
132
133 9
	private function validateInputValues($input)
134
	{
135 9
		$errors = [];
136 9
		foreach ($this->tableDefinition as $colName => $definition) {
137
			// Validation check 1: If validate function is present
138 9
			if (array_key_exists($colName, $input) 
139 9
				&& is_callable($definition['validate'] ?? null)) {
140 6
				$inputValue = $input[$colName];
141
142
				// If validation function fails
143 6
				[$status, $message] = $definition['validate']($inputValue);
144 6
				if (!$status) {
145 2
					$errors[$colName] = $message;
146
				}	
147
			}
148
149
			// Validation check 2: If relation column, check whether entity exists
150 9
			$properties = $definition['properties'] ?? null;
151 9
			if (isset($definition['relation'])
152 9
				&& ($properties & ColumnProperty::NOT_NULL)) {
153
				$instance = clone $definition['relation'];
154
				try {
155
					$instance->read($input[$colName] ?? null);
156
				} catch (ActiveRecordException $e) {
157 9
					$errors[$colName] = "Entity for this value doesn't exist";
158
				}
159
			}
160
		}
161 9
		return $errors;
162
	}
163
164
	/**
165
	 * This function is only used for API Update calls (direct getter/setter functions are unconstrained)
166
	 */
167 9
	private function validateMissingKeys()
168
	{
169 9
		$errors = [];
170
171 9
		foreach ($this->tableDefinition as $colName => $colDefinition) {
172 9
			$default = $colDefinition['default'] ?? null;
173 9
			$properties = $colDefinition['properties'] ?? null;
174 9
			$value = $colDefinition['value'];
175
176
			// If nullable and default not set => null
177
			// If nullable and default null => default (null)
178
			// If nullable and default set => default (value)
179
180
			// if not nullable and default not set => error
181
			// if not nullable and default null => error
182
			// if not nullable and default st => default (value)
183
			// => if not nullable and default null and value not set => error message in this method
184 9
			if ($properties & ColumnProperty::NOT_NULL
185 9
				&& $default === null
186 9
				&& !($properties & ColumnProperty::AUTO_INCREMENT)
187
				// && !array_key_exists($colName, $input)
188 9
				&& $value === null) {
189 9
				$errors[$colName] = sprintf("The required field \"%s\" is missing", $colName);
190
			}
191
		}
192
193 9
		return $errors;
194
	}
195
196
	/**
197
	 * Copies the values for entries in the input with matching variable names in the record definition
198
	 * @param Array $input The input data to be loaded into $this record
199
	 */
200 9
	private function loadData($input)
201
	{
202 9
		foreach ($this->tableDefinition as $colName => $definition) {
203 9
			if (array_key_exists($colName, $input)) {
204 9
				$definition['value'] = $input[$colName];
205
			}
206
		}
207 9
	}
208
209
	/**
210
	 * @param Array $input Associative array of input values
211
	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
212
	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
213
	 * 					of the modified data.
214
	 */
215 5
	public function apiCreate($input, Array $fieldWhitelist)
216
	{
217
		// Clone $this to new instance (for restoring if validation goes wrong)
218 5
		$transaction = $this->newInstance();
0 ignored issues
show
Bug introduced by
It seems like newInstance() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

218
		/** @scrutinizer ignore-call */ 
219
  $transaction = $this->newInstance();
Loading history...
219 5
		$errors = [];
220
221
		// Filter out all non-whitelisted input values
222 5
		$input = $this->filterInputColumns($input, $fieldWhitelist);
223
224
		// Validate excess keys
225 5
		$errors += $transaction->validateExcessKeys($input);
226
227
		// Validate input values (using validation function)
228 5
		$errors += $transaction->validateInputValues($input);
229
230
		// "Copy" data into transaction
231 5
		$transaction->loadData($input);
232
233
		// Run create hooks
234 5
		foreach ($this->registeredCreateHooks as $colName => $fn) {
235
			$fn();
236
		}
237
238
		// Validate missing keys
239 5
		$errors += $transaction->validateMissingKeys();
240
241
		// If no errors, commit the pending data
242 5
		if (empty($errors)) {
243 2
			$this->syncInstances($this, $transaction);
244
245
			try {
246 2
				(new Query($this->getPdo(), $this->getTableName()))
247 2
					->insert($this->getActiveRecordColumns())
248 2
					->execute();
249
250 2
				$this->setId(intval($this->getPdo()->lastInsertId()));
251
			} catch (\PDOException $e) {
252
				// @TODO: Potentially filter and store mysql messages (where possible) in error messages
253
				throw new ActiveRecordException($e->getMessage(), 0, $e);
254
			}
255
256 2
			return [null, $this->toArray($fieldWhitelist)];
257
		} else {
258 3
			return [$errors, null];
259
		}
260
	}
261
262
	/**
263
	 * @param Array $input Associative array of input values
264
	 * @param Array $fieldWhitelist array of column names that are allowed to be filled by the input array 
265
	 * @return Array Array containing the set of optional errors (associative array) and an optional array representation (associative)
266
	 * 					of the modified data.
267
	 */
268 4
	public function apiUpdate($input, Array $fieldWhitelist)
269
	{
270 4
		$transaction = $this->newInstance();
271 4
		$errors = [];
272
273
		// Filter out all non-whitelisted input values
274 4
		$input = $this->filterInputColumns($input, $fieldWhitelist);
275
276
		// Check for excess keys
277 4
		$errors += $transaction->validateExcessKeys($input);
278
279
		// Check for immutable keys
280 4
		$errors += $transaction->validateImmutableColumns($input);
281
282
		// Validate input values (using validation function)
283 4
		$errors += $transaction->validateInputValues($input);
284
285
		// "Copy" data into transaction
286 4
		$transaction->loadData($input);
287
288
		// Run create hooks
289 4
		foreach ($this->registeredUpdateHooks as $colName => $fn) {
290
			$fn();
291
		}
292
293
		// Validate missing keys
294 4
		$errors += $transaction->validateMissingKeys();
295
296
		// Update database
297 4
		if (empty($errors)) {
298 1
			$this->syncInstances($this, $transaction);
299
300
			try {
301 1
				(new Query($this->getPdo(), $this->getTableName()))
302 1
					->update($this->getActiveRecordColumns())
303 1
					->where(Query::Equal('id', $this->getId()))
0 ignored issues
show
Bug introduced by
It seems like $this->getId() can also be of type integer; however, parameter $right of miBadger\Query\Query::Equal() does only seem to accept miBadger\Query\any, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

303
					->where(Query::Equal('id', /** @scrutinizer ignore-type */ $this->getId()))
Loading history...
304 1
					->execute();
305
			} catch (\PDOException $e) {
306
				throw new ActiveRecordException($e->getMessage(), 0, $e);
307
			}
308
309 1
			return [null, $this->toArray($fieldWhitelist)];
310
		} else {
311 3
			return [$errors, null];
312
		}
313
	}
314
315
	/**
316
	 * Returns this active record after reading the attributes from the entry with the given identifier.
317
	 *
318
	 * @param mixed $id
319
	 * @return $this
320
	 * @throws ActiveRecordException on failure.
321
	 */
322
	abstract public function read($id);
323
324
	/**
325
	 * Returns the PDO.
326
	 *
327
	 * @return \PDO the PDO.
328
	 */
329
	abstract public function getPdo();
330
331
	/**
332
	 * Set the ID.
333
	 *
334
	 * @param int $id
335
	 * @return $this
336
	 */
337
	abstract protected function setId($id);
338
339
	/**
340
	 * Returns the ID.
341
	 *
342
	 * @return null|int The ID.
343
	 */
344
	abstract protected function getId();
345
346
	/**
347
	 * Returns the active record table.
348
	 *
349
	 * @return string the active record table name.
350
	 */
351
	abstract protected function getTableName();
352
353
	/**
354
	 * Returns the name -> variable mapping for the table definition.
355
	 * @return Array The mapping
356
	 */
357
	abstract protected function getActiveRecordColumns();
358
}
359