Extension:Validator

Description
Validator is a MediaWiki extension that provides generic parameter handling support to other extensions. It can be used for parameter handling parser functions and tag extensions, as well as everything else that provides an array of raw parameters. The code using Validator only needs to pass along these raw parameters, and an array containing parameter definitions, which describe what parameter should look like, how to precess them, and what to do about possible errors.

Functionality overview
Ordered roughly in execution order.


 * Name/value parsing: Raw parameters are pared to key-value pairs by splitting them on the equals sign. You can optionally provide an array of default parameter names, which will be assumed for parameters not containing any equals sign.
 * Aliasing support: You can define aliases for parameter names, which will internally be mapped to the actual parameter name.
 * Validation: Parameter values are validated against their matching parameter definition. Dependency handling is supported. Lists are supported. Warning and errors are stored and can be retrieved.
 * Correction: Incorrect parameters can be set to their default values.
 * Error reports: Since errors and warnings are stored, reports can be viewed, and further execution of the code the parameters belong to can be aborted.
 * Output formatting: Values can be returned in an alternate notation, such as a csv string containing unique items. This can make the output values usable without further handling, and works in a centralized fashion. You can add your own formats via a hook.

Download

 * Validator0.2.2.zip 32.9 KB
 * Validator0.2.2.7z 27.2 KB

You can find older version in the legacy downloads section of the version history page.

Subversion downloads
You can also download the code directly via SVN from the MediaWiki source code repository, at http://svn.wikimedia.org/svnroot/mediawiki/tags/extensions/Validator/REL_0_2_2. From a command line, you can call the following:

svn checkout http://svn.wikimedia.org/svnroot/mediawiki/tags/extensions/Validator/REL_0_2_2 Validator

Package downloads
Validator comes bundled with every release of Maps and Semantic Maps.

Installation
Once you have downloaded the code, place the 'Validator' directory within your MediaWiki 'extensions' directory. Then add the following code to your LocalSettings.php file:

Note that you need to place this code before the inclusion of any extensions depending on Validator.

Version
Validator is currently at version 0.3, and should be considered as beta. Version 0.3 is mainly released for Maps and Semantic Maps 0.6, and contains still unfinished functionality.

Planned features
The underneath list contains a list of planned features:

Features that should be implemented at some point:


 * Validator class: Break on fatal errors, such as missing required parameters that are dependencies.
 * Validator class: Correct invalid parameters in the main loop, as to have correct dependency handling.
 * ValidatorManager class: Missing required params should result in a no-go, no matter of the error level, as they can/are not defaulted.
 * ValidatorManager class: Make a distinction between fatal errors and regular errors by using 2 separate error levels. Update messages.

Idea's for features that might be nice to have:


 * Add hook for parameter types.
 * Add hook for validation types error messages.

Change log
This list only contains the versions and their release dates. For a list of all changes made, view the change log.


 * Version 0.3 (2010-05-xx)


 * Version 0.2 (2009-12-25)
 * Version 0.2.1 (2010-02-01)
 * Version 0.2.2 (2010-03-01)


 * Version 0.1 (2009-12-17)

Supported languages
Validator has support for English, Afrikaans, Belarusian, Breton, Bosnian, Lower Sorbian, Spanish, French, Galician, Swiss German, Upper Sorbian, Hungarian, Interlingua, Indonesian, Japanese, Ripoarisch, Luxembourgish, Macedonian, Dutch, Piedmontese, Portuguese, Russian, Sinhala, Swedish, Ukrainian, Vietnamese and others.

Parameter definition
This section contains detailed explanations of how each parameter definition element works. These examples can give you an idea of what a realistic parameter definition looks like:

A simple integer parameter named 'zoom' that only accepts values in the range [0, 15[. 'zoom' => array(	'type' => 'integer',	'criteria' => array( 'in_range' => array(0, 15) )	),

The most complex parameter definition found in the Maps extension, of a parameter that accepts a list of strings that need to be in an array fetched by self::getControlNames, need to be outputted as a list enumeration with a comma as delimiter and ' as wrapper, and has as default items $egMapsGMapControls. 'controls' => array(	'type' => array('string', 'list'),	'criteria' => array( 'in_array' => self::getControlNames ),	'default' => $egMapsGMapControls,	'output-type' => array('list', ',', '\'')	),

All parameter definition elements are optional. You can define a parameter without any extra information, like done below, without any problem.

'style' => array,

Aliases
Key:

The aliases element allows you to define synonyms for the main parameter name, which is hold as the key of your parameter definition. For example, if you define a 'centre' parameter, with 'center' as an alias, both parameters will be treated as if they where the same.

'centre' => array(	'aliases' => array('center'),	),

The value assigned to the aliases key should be an array containing all aliases as strings. When the aliases definition is omitted, Validator will assume there are no aliases for your parameter.

Required
Key:

The required element allows you to indicate if the parameter is required. If it is not required, and the parameter is not provided, the default value will be assigned. If it is however required, Validator will add a 'missing required parameter' error.

The value assigned to the required key should be a boolean. When the required definition is omitted, Validator will assume your parameter is not required.

Example:

'centre' => array(	'required' => true,	),

Default value
Key:

Obviously, the default element allows you to set a default value for your parameter. This value will be used to correct the values of invalid parameters, and to set those of not provide, non-required, parameters.

The type of the default value depends on the parameter type being a list or not. If it's a list, the default needs to be an array. If it's not a list, the default needs to be a single value.

Integer example:

'zoom' => array(	'default' => 10,

List of string example:

'layers' => array(	'default' => array('a', 'b', 'c'),

Type
Key:

The underneath table contains all build in parameter types. If you want do add your own type with custom behaviour, look at how to hook a parameter type.

Example of an integer type definition 'type' =>'integer'

Lists
Key: part of

Since version 0.2, you can specify lists of a certain type. For example, you can have a list of integers, or a list of strings.

You can specify a parameter is a list of a type, instead of just a single value of a type, by changing your type definition into an array, and adding the list identifier as second element. The underneath examples demonstrate how to define a list of integers.

Integer list type definition 'type' => array('integer', 'list')

You can also specify the delimiter for the list, by adding it as third element to your type definition array. When omitted, comma will be assumed.

Integer list type definition with custom delimiter 'type' => array('integer', 'list', ';')

Criteria
Key:

The underneath table contains all build in parameter criteria types. If you want do add your own type with custom criteria, look at how to hook a criteria type.

These criteria look at single values. If the type of the parameter is a list, every list item of the value will be checked against these criteria. If you want to validate a list as a whole however, you need to use list criteria.



List criteria
Key:

List criteria are criteria that look at a list as a whole, not the individual values. Like regular criteria, you can add your own custom ones, see how to hook a criteria type.

Output type
Key:  or

The output type element allows you to specify additional formatting that needs to be done with the parameter value, before it is retrieved from Validator. Important to know is that validator holds all values in string form. List types are hold in an array of strings. The obvious use of the output type is to convert these representations to something directly usable by your code.

The underneath table contains the build in output types. You can also add your own custom types.

If you only need to do one manipulation, you can use the  key. However, when you need to do multiple, you should use. The only difference between  and   is that   will expect an array of output types. This array can be empty or contain only one item, still, it needs to be an array. Keep in mind that when working with multiple output types, the ones defined first will get executed first.

Example showing how you can set the output type to 'list'. 'output-type' => 'list'

This example does the same as the above one, by using the  key. 'output-types' => array('list')

This example demonstrates how you can add multiple output types. 'output-types' => array('list')

You can also specify extra parameters for certain output types, to change the behaviour of the manipulation they perform. A good example is the list format, which accepts an optional delimiter and optional wrapper. Simply change the output type name into an array that holds the output type name as first element, and the parameters as successive ones. The amount, optionality, and order of these parameters is entirely defined by the output type.

This example is identical to the first one. 'output-type' => array('list')

Here you have 2 extra parameters added, the first one is the delimiter, the second one is the wrapper. 'output-type' => array('list', ';', '\'')

A similar example, but for. 'output-types' => array(    array('boolstr')     array('list', ';', '\'')     )

Validator class
This class provides the methods required to validate your parameters, track the errors and set any default values. In most cases you'll want to do parameter validation via class ValidatorManager, which will create an instance of a Validator. You are entirely free to directly call the Validator class to do any custom interaction, like error message generation.

For an example of how to interact with this class, see the source of ValidatorManager.

Validator settings
Validator allows you to set certain behaviours by changing a static field.


 * $storeUnknownParameters: (boolean) Indicates whether parameters not found in the criteria list be stored in case they are not accepted. The default is false.
 * $accumulateParameterErrors: (boolean) Indicates whether parameters not found in the criteria list should be stored in case they are not accepted. The default is false.
 * $acceptOverriding: (boolean) Indicates whether parameters that are provided more then once should be accepted, and use the first provided value, or not, and generate an error. The default is false.
 * $perItemValidation: (boolean) Indicates if errors in list items should cause the item to be omitted, versus having the whole list be set to it's default. The default is true.

Hooking parameter types
Validator does not support this yet. This is planned for Validator 0.3.

Hooking criteria types
You can add new criteria types to Validator using the static addValidationFunction method of the Validator class. You can use this function to override existing criteria type handlers. It has 2 parameters:
 * $criteriaName: (string) The name of the cirteria.
 * $functionName: (array) The functions location. If it's a global function, only the name, if it's in a class, first the class name, then the method name.

An usage example of the Maps extension:

To add a list validation function, which means, a validation function that validates a list as a whole, not the individual values, you need to use the addListValidationFunction function, which works identical to addValidationFunction.

A fictional example:

Validation functions are called with these parameters:


 * mixed $value: The value that is the complete list, or a single item.
 * string $name: For lookups in the param info array.
 * array $parameters: All data about the parameters gathered so far (this includes dependencies!).
 * Criteria info as provided by the parameter definition. This can be zero or more parameters.

Hooking output types
You can add new output types to Validator using the static addOutputFormat method of the Validator class. You can use this function to override existing output type handlers. It has 2 parameters:
 * $formatName: (string) The name of the cirteria.
 * $functionName: (array) The functions location. If it's a global function, only the name, if it's in a class, first the class name, then the method name.

An usage example of the Maps extension:

Formatting functions are called with these parameters:


 * mixed $value: The value that is the complete list, or a single item. ByRef for easy manipulation.
 * string $name: For lookups in the param info array.
 * array $parameters: All data about the parameters gathered so far (this includes dependencies!).
 * Output type info as provided by the parameter definition. This can be zero or more parameters.

ValidatorManager class
The ValidatorManager class contains wrapper functions for the most common interaction with the Validator class. It contains 2 methods:


 * manageParameters: Validates the provided parameters, and corrects them depending on the error level. Returns the valid parameters or false when the output should not be shown. The later is determined by the current $egValidatorFatalLevel.
 * getErrorList: Returns a string containing an HTML error list, or an empty string when there are no errors.

This is an example of how to use this class, copied from Maps 0.6 (view on SVN):

Error level
The error level is a setting defined by Validator that indicates in which situations errors should be shown, and how extensive they should be. Validator uses this setting internally in the ValidationManager class to generate error messages. Extensions using Validator can also use this setting in their own code, if not all error handling goes via Validator. An example of such an implementation can be found in the Maps extension, where maps will not be shown when there are no valid coordinates. Maps will only show a warning when the error level is equal to or above Validator_ERRORS_MINIMAL.

The error level can be set by changing the value of $egValidatorErrorLevel in LocalSettings.php, after the inclusion of Validator. The default is Validator_ERRORS_SHOW.

The possible error level values are discussed below. Note that the described behaviours are implemented in Validator, but not necessary in all extensions using Validator. The later is the task of the authors of the extensions using Validator.

None
Value:

No errors will be shown under any circumstances, including these where no output can be shown for the input of which the parameters got validated.

Warn
Value:

A warning will be shown when there are errors present. Any present errors will be treated as best as they can, by means of defaulting.

Show


Value:

All present errors will be reported in the form of a list. Any present errors will be treated as best as they can, by means of defaulting.

Strict
Value:

All present errors will be reported in the form of a list. If there is at least one error, even if it can be solved by means of defaulting, the regular output will not be generated and shown. To see the regular output, the user will first have to fix the reported errors.

Bugs and patches
If you found some bug and fixed it, please create a patch by going to the "Validator" directory, and typing:

svn diff >descriptivename.patch

Then add the patch to the bugs page. Bug reports should also be added here. You can also send them to Jeroen De Dauw, jeroendedauw -at- gmail.com.

Feature requests
Feel free to add feature requests to the discussion page.

Translating
Translation of Maps is done through translatewiki.net. The translation for this extension can be found here. To add language values or change existing ones, you should create an account on translatewiki.net, then request permission from the administrators to translate a certain language or languages on this page (this is a very simple process). Once you have permission for a given language, you can log in and add or edit whatever messages you want to in that language.

Translations for this documentation, especially the extension description, are also welcome.

Extensions that use Validator

 * Maps (Since 0.5)
 * Semantic Maps (Since 0.5)