wiki.techinc.nl/includes/libs/ParamValidator
Translation updater bot d98eb89fde
Localisation updates from https://translatewiki.net.
Change-Id: I74e0d5d5903b884e939d9a9dc61f56d84a26a4b0
2024-08-08 09:04:27 +02:00
..
i18n Localisation updates from https://translatewiki.net. 2024-08-08 09:04:27 +02:00
TypeDef Replace gettype() with get_debug_type() in exception messages 2024-07-31 19:24:39 +02:00
Util Add "implements Stringable" to every class with "function __toString()" 2024-06-13 00:23:39 +00:00
Callbacks.php
ParamValidator.php REST: force multi-value to be an array in json. 2024-07-19 10:48:07 +02:00
README.md
SimpleCallbacks.php
TypeDef.php REST: avoid crash on non-strings in request body 2024-07-16 17:18:31 +00:00
ValidationException.php

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