Trying to get away with returning a single code and parameter-list that was supposed to represent both human-readable and machine-readable data was a mistake. This patch converts it to use DataMessageValue, which represents the two separately and also provides guidance for supplying translations of all the error codes. This also eliminates the "describeSettings()" method that was trying to serve multiple use cases (in terms of the Action API, action=paraminfo and action=help). It's replaced by two methods that each serve one of the use cases. Also some of the functionality was moved out of the TypeDef base class into ParamValidator, to better match where the constants themselves live. Also I wound up creating a NumericDef base class so FloatDef can share the same range-checking logic that IntegerDef has. I probably should have done that as a separate patch, but untangling it now would be too much work. Bug: T235801 Change-Id: Iea6d4a1d05bb4b92d60415b0f03ff9d3dc99a80b |
||
|---|---|---|
| .. | ||
| i18n | ||
| TypeDef | ||
| Util | ||
| Callbacks.php | ||
| ParamValidator.php | ||
| README.md | ||
| SimpleCallbacks.php | ||
| TypeDef.php | ||
| 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 = ...;
/* @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