| 1 | Wikimedia API Parameter Validator |
| 2 | ================================= |
| 3 | |
| 4 | This library implements a system for processing and validating parameters to an |
| 5 | API from data like that in PHP's `$_GET`, `$_POST`, and `$_FILES` arrays, based |
| 6 | on a declarative definition of available parameters. |
| 7 | |
| 8 | Usage |
| 9 | ----- |
| 10 | |
| 11 | <pre lang="php"> |
| 12 | use Wikimedia\ParamValidator\ParamValidator; |
| 13 | use Wikimedia\ParamValidator\TypeDef\IntegerDef; |
| 14 | use Wikimedia\ParamValidator\SimpleCallbacks as ParamValidatorCallbacks; |
| 15 | use Wikimedia\ParamValidator\ValidationException; |
| 16 | |
| 17 | // We assume these are available from your environment in some manner. |
| 18 | /** @var Wikimedia\ObjectFactory\ObjectFactory $objectFactory */ |
| 19 | $objectFactory = ...; |
| 20 | /** @var Wikimedia\Message\MessageFormatterFactory $messageFormatterFactory */ |
| 21 | $messageFormatterFactory = ...; |
| 22 | |
| 23 | $validator = new ParamValidator( |
| 24 | new ParamValidatorCallbacks( $_POST + $_GET, $_FILES ), |
| 25 | $objectFactory |
| 26 | ); |
| 27 | |
| 28 | try { |
| 29 | $intValue = $validator->getValue( 'intParam', [ |
| 30 | ParamValidator::PARAM_TYPE => 'integer', |
| 31 | ParamValidator::PARAM_DEFAULT => 0, |
| 32 | IntegerDef::PARAM_MIN => 0, |
| 33 | IntegerDef::PARAM_MAX => 5, |
| 34 | ] ); |
| 35 | } catch ( ValidationException $ex ) { |
| 36 | $error = $messageFormatterFactory->getTextFormatter( 'en' )->format( $ex->getFailureMessage() ); |
| 37 | echo "Validation error: $error\n"; |
| 38 | } |
| 39 | </pre> |
| 40 | |
| 41 | Failure reporting |
| 42 | ----------------- |
| 43 | |
| 44 | This library uses Wikimedia\Message\DataMessageValue objects to report errors |
| 45 | in both human-readable and machine-readable formats. Basic i18n for all errors |
| 46 | generated by the library is included. |
| 47 | |
| 48 | For possible failure codes and their parameters, see the documentation of the |
| 49 | relevant `PARAM_*` constants and TypeDef classes. |
| 50 | |
| 51 | Running tests |
| 52 | ------------- |
| 53 | |
| 54 | composer install --prefer-dist |
| 55 | composer test |