Completed
Push — master ( cb0578...28965e )
by Jeroen De
07:11 queued 04:27
created

src/Processor.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace ParamProcessor;
4
5
/**
6
 * Class for parameter validation of a single parser hook or other parametrized construct.
7
 *
8
 * @since 0.1
9
 *
10
 * @licence GNU GPL v2+
11
 * @author Jeroen De Dauw < [email protected] >
12
 * @author Daniel Werner
13
 */
14
class Processor {
15
16
	/**
17
	 * Flag for unnamed default parameters used in Processor::setFunctionParams() to determine that
18
	 * a parameter should not have a named fallback.
19
	 *
20
	 * @since 0.4.13
21
	 */
22
	const PARAM_UNNAMED = 1;
23
24
	/**
25
	 * Array containing the parameters.
26
	 *
27
	 * @since 0.4
28
	 *
29
	 * @var Param[]
30
	 */
31
	private $params;
32
33
	/**
34
	 * Associative array containing parameter names (keys) and their user-provided data (values).
35
	 * This list is needed because additional parameter definitions can be added to the $parameters
36
	 * field during validation, so we can't determine in advance if a parameter is unknown.
37
	 *
38
	 * @since 0.4
39
	 *
40
	 * @var string[]
41
	 */
42
	private $rawParameters = [];
43
44
	/**
45
	 * Array containing the names of the parameters to handle, ordered by priority.
46
	 *
47
	 * @since 0.4
48
	 *
49
	 * @var string[]
50
	 */
51
	private $paramsToHandle = [];
52
53
	/**
54
	 *
55
	 *
56
	 * @since 1.0
57
	 *
58
	 * @var IParamDefinition[]
59
	 */
60
	private $paramDefinitions = [];
61
62
	/**
63
	 * List of ProcessingError.
64
	 *
65
	 * @since 0.4
66
	 *
67
	 * @var ProcessingError[]
68
	 */
69
	private $errors = [];
70
71
	/**
72
	 * Options for this validator object.
73
	 *
74
	 * @since 1.0
75
	 *
76
	 * @var Options
77
	 */
78
	private $options;
79
80
	/**
81
	 * Constructor.
82
	 *
83
	 * @param Options $options
84
	 *
85
	 * @since 1.0
86
	 */
87 15
	public function __construct( Options $options ) {
88 15
		$this->options = $options;
89 15
	}
90
91
	/**
92
	 * Constructs and returns a Validator object based on the default options.
93
	 *
94
	 * @since 1.0
95
	 *
96
	 * @return Processor
97
	 */
98 4
	public static function newDefault() {
99 4
		return new Processor( new Options() );
100
	}
101
102
	/**
103
	 * Constructs and returns a Validator object based on the provided options.
104
	 *
105
	 * @since 1.0
106
	 *
107
	 * @param Options $options
108
	 *
109
	 * @return Processor
110
	 */
111 11
	public static function newFromOptions( Options $options ) {
112 11
		return new Processor( $options );
113
	}
114
115
	/**
116
	 * Returns the options used by this Validator object.
117
	 *
118
	 * @since 1.0
119
	 *
120
	 * @return Options
121
	 */
122 1
	public function getOptions() {
123 1
		return $this->options;
124
	}
125
126
	/**
127
	 * Determines the names and values of all parameters. Also takes care of default parameters.
128
	 * After that the resulting parameter list is passed to Processor::setParameters
129
	 *
130
	 * @since 0.4
131
	 *
132
	 * @param array $rawParams
133
	 * @param array $parameterInfo
134
	 * @param array $defaultParams array of strings or array of arrays to define which parameters can be used unnamed.
135
	 *        The second value in array-form is reserved for flags. Currently, Processor::PARAM_UNNAMED determines that
136
	 *        the parameter has no name which can be used to set it. Therefore all these parameters must be set before
137
	 *        any named parameter. The effect is, that '=' within the string won't confuse the parameter anymore like
138
	 *        it would happen with default parameters that still have a name as well.
139
	 */
140
	public function setFunctionParams( array $rawParams, array $parameterInfo, array $defaultParams = [] ) {
141
		$parameters = [];
142
143
		$nr = 0;
144
		$defaultNr = 0;
145
		$lastUnnamedDefaultNr = -1;
146
147
		/*
148
		 * Find last parameter with self::PARAM_UNNAMED set. Tread all parameters in front as
149
		 * the flag were set for them as well to ensure that there can't be any unnamed params
150
		 * after the first named param. Wouldn't be possible to determine which unnamed value
151
		 * belongs to which parameter otherwise.
152
		 */
153
		for( $i = count( $defaultParams ) - 1; $i >= 0 ; $i-- ) {
154
			$dflt = $defaultParams[$i];
155
			if( is_array( $dflt ) && !empty( $dflt[1] ) && ( $dflt[1] | self::PARAM_UNNAMED ) ) {
156
				$lastUnnamedDefaultNr = $i;
157
				break;
158
			}
159
		}
160
161
		foreach ( $rawParams as $arg ) {
162
			// Only take into account strings. If the value is not a string,
163
			// it is not a raw parameter, and can not be parsed correctly in all cases.
164
			if ( is_string( $arg ) ) {
165
				$parts = explode( '=', $arg, ( $nr <= $lastUnnamedDefaultNr ? 1 : 2 ) );
166
167
				// If there is only one part, no parameter name is provided, so try default parameter assignment.
168
				// Default parameters having self::PARAM_UNNAMED set for having no name alias go here in any case.
169
				if ( count( $parts ) == 1 ) {
170
					// Default parameter assignment is only possible when there are default parameters!
171
					if ( count( $defaultParams ) > 0 ) {
172
						$defaultParam = array_shift( $defaultParams );
173
						if( is_array( $defaultParam ) ) {
174
							$defaultParam = $defaultParam[0];
175
						}
176
						$defaultParam = strtolower( $defaultParam );
177
178
						$parameters[$defaultParam] = [
179
							'original-value' => trim( $parts[0] ),
180
							'default' => $defaultNr,
181
							'position' => $nr
182
						];
183
						$defaultNr++;
184
					}
185
					else {
0 ignored issues
show
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
186
						// It might be nice to have some sort of warning or error here, as the value is simply ignored.
187
					}
188
				} else {
189
					$paramName = trim( strtolower( $parts[0] ) );
190
191
					$parameters[$paramName] = [
192
						'original-value' => trim( $parts[1] ),
193
						'default' => false,
194
						'position' => $nr
195
					];
196
197
					// Let's not be evil, and remove the used parameter name from the default parameter list.
198
					// This code is basically a remove array element by value algorithm.
199
					$newDefaults = [];
200
201
					foreach( $defaultParams as $defaultParam ) {
202
						if ( $defaultParam != $paramName ) $newDefaults[] = $defaultParam;
203
					}
204
205
					$defaultParams = $newDefaults;
206
				}
207
			}
208
209
			$nr++;
210
		}
211
212
		$this->setParameters( $parameters, $parameterInfo );
213
	}
214
215
	/**
216
	 * Loops through a list of provided parameters, resolves aliasing and stores errors
217
	 * for unknown parameters and optionally for parameter overriding.
218
	 *
219
	 * @param array $parameters Parameter name as key, parameter value as value
220
	 * @param IParamDefinition[] $paramDefinitions List of parameter definitions. Either ParamDefinition objects or equivalent arrays.
221
	 */
222 12
	public function setParameters( array $parameters, array $paramDefinitions ) {
223 12
		$this->paramDefinitions = ParamDefinition::getCleanDefinitions( $paramDefinitions );
224
225
		// Loop through all the user provided parameters, and distinguish between those that are allowed and those that are not.
226 12
		foreach ( $parameters as $paramName => $paramData ) {
227 10
			if ( $this->options->lowercaseNames() ) {
228 8
				$paramName = strtolower( $paramName );
229
			}
230
231 10
			if ( $this->options->trimNames() ) {
232 8
				$paramName = trim( $paramName );
233
			}
234
235 10
			$paramValue = is_array( $paramData ) ? $paramData['original-value'] : $paramData;
236
237 10
			$this->rawParameters[$paramName] = $paramValue;
238
		}
239 12
	}
240
241
	/**
242
	 * @param string $message
243
	 * @param mixed $tags string or array
244
	 * @param integer $severity
245
	 */
246 4
	private function registerNewError( $message, $tags = [], $severity = ProcessingError::SEVERITY_NORMAL ) {
247 4
		$this->registerError(
248 4
			new ProcessingError(
249
				$message,
250
				$severity,
251 4
				$this->options->getName(),
252 4
				(array)$tags
253
			)
254
		);
255 4
	}
256
257 4
	private function registerError( ProcessingError $error ) {
258 4
		$error->element = $this->options->getName();
259 4
		$this->errors[] = $error;
260 4
		ProcessingErrorHandler::addError( $error );
261 4
	}
262
263
	/**
264
	 * Validates and formats all the parameters (but aborts when a fatal error occurs).
265
	 *
266
	 * @since 0.4
267
	 * @deprecated since 1.0, use processParameters
268
	 */
269
	public function validateParameters() {
270
		$this->doParamProcessing();
271
	}
272
273
	/**
274
	 * @since 1.0
275
	 *
276
	 * @return ProcessingResult
277
	 */
278 8
	public function processParameters() {
279 8
		$this->doParamProcessing();
280
281 8
		if ( !$this->hasFatalError() && $this->options->unknownIsInvalid() ) {
282
			// Loop over the remaining raw parameters.
283
			// These are unrecognized parameters, as they where not used by any parameter definition.
284 7
			foreach ( $this->rawParameters as $paramName => $paramValue ) {
285 2
				$this->registerNewError(
286 2
					$paramName . ' is not a valid parameter', // TODO
287
					$paramName
288
				);
289
			}
290
		}
291
292 8
		return $this->newProcessingResult();
293
	}
294
295
	/**
296
	 * @return ProcessingResult
297
	 */
298 8
	private function newProcessingResult() {
299 8
		$parameters = [];
300
301 8
		if ( !is_array( $this->params ) ) {
302 3
			$this->params = [];
303
		}
304
305
		/**
306
		 * @var Param $parameter
307
		 */
308 8
		foreach ( $this->params as $parameter ) {
309
			// TODO
310 5
			$processedParam = new ProcessedParam(
311 5
				$parameter->getName(),
312 5
				$parameter->getValue(),
313 5
				$parameter->wasSetToDefault()
314
			);
315
316
			// TODO: it is possible these values where set even when the value defaulted,
317
			// so this logic is not correct and could be improved
318 5
			if ( !$parameter->wasSetToDefault() ) {
319 4
				$processedParam->setOriginalName( $parameter->getOriginalName() );
320 4
				$processedParam->setOriginalValue( $parameter->getOriginalValue() );
321
			}
322
323 5
			$parameters[$processedParam->getName()] = $processedParam;
324
		}
325
326 8
		return new ProcessingResult(
327
			$parameters,
328 8
			$this->getErrors()
329
		);
330
	}
331
332
	/**
333
	 * Does the actual parameter processing.
334
	 */
335 8
	private function doParamProcessing() {
336 8
		$this->errors = [];
337
338 8
		$this->getParamsToProcess( [], $this->paramDefinitions );
339
340 8
		while ( $this->paramsToHandle !== [] && !$this->hasFatalError() ) {
341 7
			$this->processOneParam();
342
		}
343 8
	}
344
345 7
	private function processOneParam() {
346 7
		$paramName = array_shift( $this->paramsToHandle );
347 7
		$definition = $this->paramDefinitions[$paramName];
348
349 7
		$param = new Param( $definition );
350
351 7
		$setUserValue = $this->attemptToSetUserValue( $param );
352
353
		// If the parameter is required but not provided, register a fatal error and stop processing.
354 7
		if ( !$setUserValue && $param->isRequired() ) {
355 2
			$this->registerNewError(
356 2
				"Required parameter '$paramName' is missing", // FIXME: i18n validator_error_required_missing
357 2
				[ $paramName, 'missing' ],
358 2
				ProcessingError::SEVERITY_FATAL
359
			);
360 2
			return;
361
		}
362
363 5
		$this->params[$param->getName()] = $param;
364
365 5
		$initialSet = $this->paramDefinitions;
366
367 5
		$param->process( $this->paramDefinitions, $this->params, $this->options );
368
369 5
		foreach ( $param->getErrors() as $error ) {
370 2
			$this->registerError( $error );
371
		}
372
373 5
		if ( $param->hasFatalError() ) {
374
			return;
375
		}
376
377 5
		$this->getParamsToProcess( $initialSet, $this->paramDefinitions );
378 5
	}
379
380
	/**
381
	 * Gets an ordered list of parameters to process.
382
	 *
383
	 * @since 0.4
384
	 *
385
	 * @param array $initialParamSet
386
	 * @param array $resultingParamSet
387
	 *
388
	 * @throws \UnexpectedValueException
389
	 */
390 8
	private function getParamsToProcess( array $initialParamSet, array $resultingParamSet ) {
391 8
		if ( $initialParamSet === [] ) {
392 8
			$this->paramsToHandle = array_keys( $resultingParamSet );
0 ignored issues
show
Documentation Bug introduced by
It seems like array_keys($resultingParamSet) of type array<integer,integer|string> is incompatible with the declared type array<integer,string> of property $paramsToHandle.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
393
		}
394
		else {
395 5
			if ( !is_array( $this->paramsToHandle ) ) {
396
				$this->paramsToHandle = [];
397
			}
398
399 5
			foreach ( $resultingParamSet as $paramName => $parameter ) {
400 5
				if ( !array_key_exists( $paramName, $initialParamSet ) ) {
401
					$this->paramsToHandle[] = $paramName;
402
				}
403
			}
404
		}
405
406 8
		$this->paramsToHandle = $this->getParameterNamesInEvaluationOrder( $this->paramDefinitions, $this->paramsToHandle );
407 8
	}
408
409
	/**
410
	 * @param IParamDefinition[] $paramDefinitions
411
	 * @param string[] $paramsToHandle
412
	 *
413
	 * @return array
414
	 */
415 8
	private function getParameterNamesInEvaluationOrder( array $paramDefinitions, array $paramsToHandle ) {
416 8
		$dependencyList = [];
417
418 8
		foreach ( $paramsToHandle as $paramName ) {
419 7
			$dependencies = [];
420
421 7
			if ( !array_key_exists( $paramName, $paramDefinitions ) ) {
422
				throw new \UnexpectedValueException( 'Unexpected parameter name "' . $paramName . '"' );
423
			}
424
425 7
			if ( !is_object( $paramDefinitions[$paramName] ) || !( $paramDefinitions[$paramName] instanceof IParamDefinition ) ) {
426
				throw new \UnexpectedValueException( 'Parameter "' . $paramName . '" is not a IParamDefinition' );
427
			}
428
429
			// Only include dependencies that are in the list of parameters to handle.
430 7
			foreach ( $paramDefinitions[$paramName]->getDependencies() as $dependency ) {
431
				if ( in_array( $dependency, $paramsToHandle ) ) {
432
					$dependencies[] = $dependency;
433
				}
434
			}
435
436 7
			$dependencyList[$paramName] = $dependencies;
437
		}
438
439 8
		$sorter = new TopologicalSort( $dependencyList, true );
440
441 8
		return $sorter->doSort();
442
	}
443
444
	/**
445
	 * Tries to find a matching user provided value and, when found, assigns it
446
	 * to the parameter, and removes it from the raw values. Returns a boolean
447
	 * indicating if there was any user value set or not.
448
	 *
449
	 * @since 0.4
450
	 *
451
	 * @param Param $param
452
	 *
453
	 * @return boolean
454
	 */
455 7
	private function attemptToSetUserValue( Param $param ) {
456 7
		if ( array_key_exists( $param->getName(), $this->rawParameters ) ) {
457 5
			$param->setUserValue( $param->getName(), $this->rawParameters[$param->getName()], $this->options );
458 5
			unset( $this->rawParameters[$param->getName()] );
459 5
			return true;
460
		}
461
		else {
462 5
			foreach ( $param->getDefinition()->getAliases() as $alias ) {
463
				if ( array_key_exists( $alias, $this->rawParameters ) ) {
464
					$param->setUserValue( $alias, $this->rawParameters[$alias], $this->options );
465
					unset( $this->rawParameters[$alias] );
466
					return true;
467
				}
468
			}
469
		}
470
471 5
		return false;
472
	}
473
474
	/**
475
	 * Returns the parameters.
476
	 *
477
	 * @since 0.4
478
	 * @deprecated since 1.0
479
	 *
480
	 * @return IParam[]
481
	 */
482
	public function getParameters() {
483
		return $this->params;
484
	}
485
486
	/**
487
	 * Returns a single parameter.
488
	 *
489
	 * @since 0.4
490
	 * @deprecated since 1.0
491
	 *
492
	 * @param string $parameterName The name of the parameter to return
493
	 *
494
	 * @return IParam
495
	 */
496
	public function getParameter( $parameterName ) {
497
		return $this->params[$parameterName];
498
	}
499
500
	/**
501
	 * Returns an associative array with the parameter names as key and their
502
	 * corresponding values as value.
503
	 *
504
	 * @since 0.4
505
	 *
506
	 * @return array
507
	 */
508
	public function getParameterValues() {
509
		$parameters = [];
510
511
		foreach ( $this->params as $parameter ) {
512
			$parameters[$parameter->getName()] = $parameter->getValue();
513
		}
514
515
		return $parameters;
516
	}
517
518
	/**
519
	 * Returns the errors.
520
	 *
521
	 * @since 0.4
522
	 *
523
	 * @return ProcessingError[]
524
	 */
525 8
	public function getErrors() {
526 8
		return $this->errors;
527
	}
528
529
	/**
530
	 * @since 0.4.6
531
	 *
532
	 * @return string[]
533
	 */
534
	public function getErrorMessages() {
535
		$errors = [];
536
537
		foreach ( $this->errors as $error ) {
538
			$errors[] = $error->getMessage();
539
		}
540
541
		return $errors;
542
	}
543
544
	/**
545
	 * Returns if there where any errors during validation.
546
	 *
547
	 * @return boolean
548
	 */
549
	public function hasErrors() {
550
		return !empty( $this->errors );
551
	}
552
553
	/**
554
	 * Returns false when there are no fatal errors or an ProcessingError when one is found.
555
	 *
556
	 * @return ProcessingError|boolean false
557
	 */
558 8
	public function hasFatalError() {
559 8
		foreach ( $this->errors as $error ) {
560 4
			if ( $error->isFatal() ) {
561 2
				return $error;
562
			}
563
		}
564
565 8
		return false;
566
	}
567
568
}
569