Extension:Validator/0.3.6

Note: this article is about version 0.3.6 of Validator. See this page for the documentation of the current version.

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.3.zip 37.7 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_3_3. From a command line, you can call the following:

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

To get the latest version of Validator, just check out from svn trunk, at http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/Validator. The distribution archive downloads are only made for big releases, so lag behind the actual version most of the time.

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

Package downloads
Validator comes bundled with every release of Maps and Semantic Maps. You can get their distributions here.

Installation
Once you have downloaded the code, place the 'Validator' directory within your MediaWiki 'extensions' directory. Then add the following code to your 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.6, and should be considered as beta. Version 0.3.x is mainly released for Maps and Semantic Maps 0.6.x, and contains still unfinished functionality.

New features

 * Listerrors parser hook that allows displaying all errors that occurred until that point. Similar concept to the references tag extension.
 * Full extendibility of parameter criteria.
 * ParserHook class that provides out-of-the-box seamless integration with Validator and hides parser hook complexity that's not needed for almost everything.
 * Parameter definition list manipulation during validation.

Refactoring

 * Big rewrite to make Validator more OO, instead of array-based.

Other idea's
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-31)
 * Version 0.3.1 (2010-06-04)
 * Version 0.3.2 (2010-06-07)
 * Version 0.3.3 (2010-06-20)
 * Version 0.3.4 (2010-07-08)
 * Version 0.3.5 (2010-07-26)
 * Version 0.3.6 (2010-08-26)


 * 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) )	),

Here is an example of a complex parameter definition. This is a parameter found in the Maps extension.

The controls parameter accepts a list of strings. Each string must be in the array returned by self::getControlNames. After the parameter is validated, the list of strings is returned as a single string with each value delimited by a comma and enclosed in a single quote (').

The default is the value of $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. The simplest way to define a parameter named “style” is: '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.

By default, there are no aliases.

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.

By default, parameters are not required.

Example:

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

Default value
Key:

The default element allows you to set a default value for your parameter. Besides providing a default for optional, unspecified parameters, this value will replace the values of invalid parameters.

The default value of a list parameter should be specified as an array. Otherwise, a scalar value should be used.

Integer example:

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

List of strings example: 'layers' => array( 'default' => array('a', 'b', 'c') )

Type
Key:

The following table contains all possible parameter types. Parameter types are not case sensitive. If you want to add your own type with custom behaviour, read Hooking parameter types.

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

Lists
Key: part of

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 following 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 providing it as third element in your type definition array. When the third element is omitted, a comma will be assumed.

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

Criteria
Key:

The following table contains the possible parameter criteria types. If you want to add your own type with a custom criteria, read Hooking criteria types.

These criteria are for scalar values. If the type of the parameter is a list, every list item of the value will be checked against the criteria. If you want to validate the list as a whole, 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. It is important to understand that Validator stores all values as strings. List types are held an array of strings. The output type is used to convert these representations to something usable by your code.

The following 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', 'unique_items')

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 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. These parameters are 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 the ValidatorManager class, which will create an instance of 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) If false (the default), then parameters not found in the criteria list be discarded.
 * accumulateParameterErrors: (boolean) If false (the default), then break on the first error. Otherwise, continue validation, accumulating all the errors along the way.
 * acceptOverriding: (boolean) Indicates whether parameters that are provided more then once should be accepted. If this is false (the default), only the first value is accepted and any later values generate an error.
 * 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</tt>: (string) The name of the criteria.
 * functionName</tt>: The function to use. See the PHP callback type for the form this should be in.

An usage example of the Maps extension:

To add a list validation function, you need to use the addListValidationFunction</tt> function, which is otherwise identical to addValidationFunction</tt>.

A fictional example:

Validation functions are called with these parameters:


 * value</tt>: (mixed) The value that is the complete list, or a single item.
 * name</tt>: (string) For lookups in the param info array.
 * parameters</tt>: (array) 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</tt> method of the Validator class. You can use this function to override existing output type handlers. It has 2 parameters:
 * formatName</tt>: (string) The name of the cirteria.
 * functionName</tt>: The function to use. See the PHP callback type for the form this should be in.

An usage example of the Maps extension:

Formatting functions are called with these parameters:


 * value</tt>: (mixed) The value that is the complete list, or a single item. ByRef for easy manipulation.
 * name</tt>: (string) For lookups in the param info array.
 * parameters</tt>: (array) 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, 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)