Extension:Validator

From MediaWiki.org
Jump to: navigation, search
MediaWiki extensions manual - list
Crystal Clear action run.png
Validator

Release status: stable

Green check.svg
Implementation Tag, Parser functions, Hook
Description Validator is a MediaWiki extension that provides generic parameter handling support to other extensions.
Author(s) Jeroen De Dauw
Last version 0.4.13 (2011-11-30)
MediaWiki 1.15.0 or later, possibly older ones
License GPL v3 or later
Download Stable releases - All versions
Example Example

Check usage (experimental)

Validator is a parameter handling framework which aims to facilitate common parameter handling tasks, such as parsing, validation, and error handling, for other MediaWiki extensions.

Contents

[edit] Functionality overview

A brief description of the core functionality.

[edit] Parameter validation

You can validate a list of raw parameters against a set of parameter definitions using the Validator class. Validator will then determine which criteria are not met, which parameters are missing and which ones are unknown. Incorrect or missing values are replaced by the default value for their parameter, and all errors are stored.

The raw parameters can be either key value pairs, such as provided by tag extensions, or 'foo=bar' elements, such as provided by parser functions. In case of the later, Validator takes care of the parsing and provides out-of-the-box support for default parameters. Validator also provides a ParserHook class which enables you to create parser hooks (tag extensions and parser functions) that seamlessly integrate with the other functionality provided by Validator.

[edit] Parameter manipulation

Validator not only Validates your parameters, but also further handles them so that you get them into a convenient format and don't need to do any further manipulations. A simple example is a parameter which expects a list of "yes" and "no", such as foobar=yes, no, no, yes, no. What validator will return is an array containing booleans. This removes the need for defining the same handling all over your code, and allows you to get right to what you actually want to write. Validator provides a set of common manipulations, which is easily extendible by other extensions to add more specific handling.

[edit] Errors and warnings

Validator provides several classes to describe and keep track of parameter validation related errors. Such errors can be shown inline or at the end of the page using the listerrors parser hook. All errors have a severity, and you can configure which actions need to be taken for errors with a certain severity. For example if they should be shown inline or not. This functionality works out-of-the-box when using the ParserHook class and the criteria classes provided by Validator in your parameter definitions, but can easily be used and extended by in other situations.

[edit] Automatic documentation generation

Since version 0.4.3, Validator has a "describe" parser hook which automatically generates documentation for one or more parser hooks. This documentation includes a description of the parser hook, a table with it's parameters and syntax examples. The result can be either directly viewed in a wiki page, or displayed as wikitext, so it can be copied over to another page. (example)

[edit] Setup

[edit] Download

You can find the current downloads on the Validator google code project. For a list of all downloads, including deprecated ones, see here.

[edit] 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/. From a command line, you can call the following (where X_X_X is the version number):

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

To get the latest version of Validator, just check out from svn trunk, at http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/Validator.

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

[edit] Package downloads

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

[edit] 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:

# Validator
require_once( "$IP/extensions/Validator/Validator.php" );

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

[edit] Change log

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

[edit] Usage

[edit] listerrors

Description: Lists errors (and warnings) that occured in parser hooks added via Validator. Only lists for parser hooks added above where listerrors is inserted; place listerrors at or near the bottom of the page to get all errors.

Implemented as both parser function and as tag extension.

[edit] Parameters

# Parameter Aliases Type Default Description
1 minseverity - Text minor The minimum severity of an issue for it to be listed.

[edit] Syntax

Tag extension with only the required parameters.

<listerrors />

Tag extension with all parameters.

<listerrors minseverity="{Text}" />

Tag extension with all parameters using the default parameter notation.

<listerrors>{minseverity, Text}</listerrors>

Parser function with only the required parameters.

{{#listerrors:}}

Parser function with all parameters.

{{#listerrors:minseverity={Text}}}

Parser function with all parameters using the default parameter notation.

{{#listerrors:{minseverity, Text}}}

[edit] describe

Description: Generates documentation for one or more parser hooks defined via Validator.

Implemented as both parser function and as tag extension.

[edit] Parameters

# Parameter Aliases Type Default Description
1 hooks - List of text items listerrors, describe, coordinates, display_map, display_point, distance, finddestination, geocode, geodistance, subpages The parser hooks for which to display documentation.
- pre - Yes/no off Allows you to get the actual wikitext for the documentation, without it being rendered on the page.

[edit] Syntax

Tag extension with only the required parameters.

<describe />

Tag extension with all parameters.

<describe hooks="{List of text items}" pre="{Yes/no}" />

Tag extension with all parameters using the default parameter notation.

<describe pre="{Yes/no}">{hooks, List of text items}</describe>

Parser function with only the required parameters.

{{#describe:}}

Parser function with all parameters.

{{#describe:hooks={List of text items}|pre={Yes/no}}}

Parser function with all parameters using the default parameter notation.

{{#describe:{hooks, List of text items}|pre=Yes/no}}

[edit] Supported languages

Validator has support for over 45 languages, including English, Afrikaans, Gheg Albanian, Arabic, Belarusian, Bulgarian, Breton, Bosnian, Czech, German, Lower Sorbian, Greek, Esperanto, Spanish, Finnish, French, Franco-Provençal, Galician, Swiss German, Hebrew, Upper Sorbian, Hungarian, Interlingua, Indonesian, Italian, Japanese, Colognian, Luxembourgish, Macedonian, Dutch, Norwegian, Occitan, Polish, Piedmontese, Portuguese, Brazilian Portuguese, Romanian, Russian, Sinhala, Swedish, Telugu, Tagalog, Turkish, Ukrainian, Vietnamese, Simplified Chinese and others.


[edit] Implementation

This section describes how you can use Validator in your own extension. Poke Jeroen De Dauw if anything here isn't clear to you.

[edit] The Validator class

Using the Validator class to handle parameters is pretty straight forward.

$validator = new Validator();
$validator->setParameters( $keyValuePairs, $paramDefinitions );
$validator->validateParameters();
 
if ( $validator->hasFatalError() ) {
    // Fatal errors usually consist of required parameter that are not provided, or the provided value is invalid.
    // You can get the errors using $validator->getErrors(); to display some error.
}
else {
    $handledKeyValuePairs = $validator->getParameterValues(); // Just get an associative array...
    $handledParams = $validator->getParameters(); // ... Or get the full parameter objects, containing stuff like original values, if they where defaulted, ect.
 
    // Do the stuff you actually care about ...
}

Variables:

  • $keyValuePairs is an associative array with the raw parameter name, parameter value combinations as obtained from user input, for example a tag extension.
  • $paramDefinitions is an array containing parameter specifications defined by you. See the parameters section for more info on this.

As a common use case is handling parser functions, Validator also has a alternate method to setParameters that directly accepts the parameters as you get them in your parser function hook.

$validator->setFunctionParams( $rawParams, $paramDefinitions, $defaultParams );

This method accepts a third, optional, parameter $defaultParams. This is an array containing the names of the default parameters (if any). Default parameters are parameters that can be assigned without specifying their name as done in |key=value|, but only specifying their value |value|.

[edit] The ParserHook class

You can quickly build parser hooks that take full advantage of the features Validator adds to MediaWiki by creating a class that derives from ParserHook. This will force you to implement methods that return the name or names of your parser hook, and that render the actual output (given the processed parameters). Examples of such classes can be found in Maps and in Validator itself.

[edit] Parameters

The Parameter class provides a way to describe a parameter and in what what ways it should be handled. These things can be specified:

[edit] Name

The only required parameter in the constructor is the name of the parameter. This is the name the user uses. It's always case-insensitive.

$yourParam = new Parameter( 'foobar' );

[edit] Type

The type of the parameter indicates if the value is supposed to be a string, an integer, a boolean, ect. Supported types are:

  • Parameter::TYPE_STRING
  • Parameter::TYPE_NUMBER
  • Parameter::TYPE_INTEGER
  • Parameter::TYPE_FLOAT
  • Parameter::TYPE_BOOLEAN
  • Parameter::TYPE_CHAR

It's the second argument in the constructor, and defaults to TYPE_STRING (so is optional).

$ageParam = new Parameter( 'age', Parameter::TYPE_INTEGER );

Setting the type to something else then string will cause one or more criteria to automatically get added to the criteria field. Integer and float also add a manipulation to the manipulations field.

[edit] Default value

The third parameter in the constructor allows you to specify the default value for the parameter. This value will be used when the parameter is either not provided, or the value is not valid.

$score = new Parameter( 'score', Parameter::TYPE_FLOAT, 4.2 );

You can also specify the default using the setDefault method.

$score->setDefault( 4.2 );

Not providing a default (or rather setting it to null) makes the parameter required. You can find out if a parameter is required using the isRequired method.

$score->isRequired();

[edit] Name aliases

You might want to interpret multiple parameter names as the same parameter. For example, when you have a parameter denoting a center, you probably want to accept both "center" and "centre", to not annoy people using the alternate spelling. This is also great for backward compatibility, as it allows renaming a parameter, and then keeping the old name as an alias for a while.

You can set the aliases either by providing the 4th argument in the constructor, which needs to be an array, or by passing a single value or an array to the addAliases method.

$score = new Parameter( 'score', Parameter::TYPE_FLOAT, null, array( 'points' ) );
$score = new Parameter( 'score', Parameter::TYPE_FLOAT );
$score->addAliases( 'points' );

[edit] Criteria field

You can specify one or more criteria the parameter should hold up against. For example, if you have a percentage, it should be in the range [0, 100]. You can pass criteria as the 5th argument in the constructor, but are probably better of adding them by use of the addCriteria method. This method accepts a single criterion or an array of criteria.

$score = new Parameter( 'percentage', Parameter::TYPE_INTEGER );
$score->addCriteria( new CriterionInRange( 0, 100 ) );

These criteria are instances of classes deriving from ParameterCriterion. A number of common ones are included in Validator by default, and you can add new ones in your own code as you like.

[edit] Manipulations field

You can specify one or more manipulations to apply to the parameter value after the validation, before returning the final value. You can add them via the addManipulations method.

$yourParam = new Parameter( 'foobar' );
$yourParam->addManipulations( new SomeManipulationClass( ...args... ) );

[edit] Dependencies

Sometimes you want the behavior of a parameter to be dependent on the value of another one, or even add parameters in relation to the value of one or more others. To allow for this, the parameters need to be handled in the correct order. You can specify parameters a single parameter is dependent on, after which Validator will determine the correct order or handling via topological sort. Dependencies can be added via the addDependencies method, which accepts one or more parameter names. Note that these should be the actual names of the parameters; aliases are not resolved.

$yourParam = new Parameter( 'foobar' );
$otherParam = new Parameter( 'baz' );
$otherParam->addDependencies( 'foobar' );

[edit] Description

The description is an internationalized message that describes the function of the parameter, allowing for automatic generation of documentation, such as done by the describe parser hook. It is completely optional and can be set via the setDescription method. This method was added in Validator 0.4.3. In recent versions of Validator (0.4.11 and later), you are encouraged to use setMessage instead. This method takes a message key (ie what you also put into wfMsg), instead of an actual message. This allows displaying the message in a language different then the current users language.

[edit] List parameters

A common behavior for parameters is that you want them to accept a list of values instead of just one. You can create such parameters using the ListParameter class. It derives from Parameter and works very similar. The type, criteria and manipulations apply to all values provided. The default value is supposed to be an array, but a single value will also be accepted, and casted to an array.

$scores = new ListParameter( 'scores', Parameter::TYPE_FLOAT );

You might want to put criteria on the list as a whole, or do some manipulation that uses all items. This is possible by adding classes deriving from ListParameterCriterion or ListParameterManipulation via the addCriteria and addManipulations methods, respectively.

You can find out if a parameter is a list parameter or not via the isList method.

[edit] Criteria

Criteria in Validator are classes deriving from either ItemParameterCriterion or ListParameterCriterion, which both derive from ParameterCriterion. They specify a single thing a parameter value, or list of values, should hold up against in order to be considered valid.

Validator comes with several of these criteria by default, which you can see here. You can also create you own. When creating your own criterion class, you should implement the abstract doValidation method, which gets passed all the info available in the parameter handling process so far. There are several other methods with optional behavior, such as specifying an error message for when validation against the criterion fails. You can check out the default criteria in Validator if you need examples, and look at the PHP docs in the base classes if you need more info on how to correctly implement the methods.

[edit] Manipulations

Manipulations in Validator are classes deriving from either ItemParameterManipulation or ListParameterManipulation, which both derive from ParameterManipulation. They specify a single action that should be applied to a parameter value, or list of values after validation was done.

They are very similar to criteria, with as main difference that these classes have the ability to easily modify the parameter value (as the value gets passes as reference). Validator comes with several of these manipulations by default, which you can see here.

[edit] Contributing to the project

[edit] 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 upload it somewhere and link to it from the talk page. Bug reports should also be added here. You can also send them to Jeroen De Dauw, jeroendedauw -at- gmail.com.

[edit] Feature requests

Feel free to add feature requests to the discussion page.

[edit] Translating

Translation of Validator 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.

[edit] Extensions that use Validator

[edit] External links

[edit] Sites that use Validator

[edit] See also

Validator Validator: IntroductionDownloadInstallationImplementationVersion historyPlanned featuresContributingBugsDiscussion
Personal tools
Namespaces
Variants
Actions
Site
Support
Download
Development
Communication
Print/export
Toolbox