wiki.techinc.nl/includes/libs/ParamValidator
2022-03-25 17:16:27 +00:00
..
i18n Localisation updates from https://translatewiki.net. 2022-02-09 08:01:45 +01:00
TypeDef ParamValidator: Disallow array values in integer param 2022-03-25 16:53:44 +00:00
Util docs: Fix nullable documentation for class properties 2021-09-24 00:54:53 +00:00
Callbacks.php ParamValidator: Use MessageValue! 2019-11-01 15:49:31 -04:00
ParamValidator.php Use updated ObjectFactory namespace 2022-03-09 23:04:51 +00:00
README.md Use updated ObjectFactory namespace 2022-03-09 23:04:51 +00:00
SimpleCallbacks.php phan: Disable null_casts_as_any_type setting 2022-03-21 18:25:07 +00:00
TypeDef.php build: Updating dependencies 2021-07-22 03:36:05 +00:00
ValidationException.php Remove some more comments that literally repeat the code 2021-12-09 19:01:36 +01:00

Wikimedia API Parameter Validator

This library implements a system for processing and validating parameters to an API from data like that in PHP's $_GET, $_POST, and $_FILES arrays, based on a declarative definition of available parameters.

Usage

use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\ParamValidator\TypeDef\IntegerDef;
use Wikimedia\ParamValidator\SimpleCallbacks as ParamValidatorCallbacks;
use Wikimedia\ParamValidator\ValidationException;

// We assume these are available from your environment in some manner.
/** @var Wikimedia\ObjectFactory\ObjectFactory $objectFactory */
$objectFactory = ...;
/** @var Wikimedia\Message\MessageFormatterFactory $messageFormatterFactory */
$messageFormatterFactory = ...;

$validator = new ParamValidator(
	new ParamValidatorCallbacks( $_POST + $_GET, $_FILES ),
	$objectFactory
);

try {
	$intValue = $validator->getValue( 'intParam', [
			ParamValidator::PARAM_TYPE => 'integer',
			ParamValidator::PARAM_DEFAULT => 0,
			IntegerDef::PARAM_MIN => 0,
			IntegerDef::PARAM_MAX => 5,
	] );
} catch ( ValidationException $ex ) {
	$error = $messageFormatterFactory->getTextFormatter( 'en' )->format( $ex->getFailureMessage() );
	echo "Validation error: $error\n";
}

Failure reporting

This library uses Wikimedia\Message\DataMessageValue objects to report errors in both human-readable and machine-readable formats. Basic i18n for all errors generated by the library is included.

For possible failure codes and their parameters, see the documentation of the relevant PARAM_* constants and TypeDef classes.

Running tests

composer install --prefer-dist
composer test