Manual:Funciones de análisis sintáctico

This page is a translated version of the page Manual:Parser functions and the translation is 41% complete.
Outdated translations are marked like this.
MediaWiki extensions

Las funciones de analizador, añadida en MediaWiki 1.7, es un tipo de extension que integra estrechamente con el analizador. The phrase "parser function" should not be confused with Extensión:ParserFunctions , which is a collection of simple parser functions. (Véase Ayuda:Extensión:ParserFunctions para esa).

Descripción

Mientras que una extensión de marcado está concebida para tomar texto sin procesar y devolver HTML al navegador, una función de análisis puede «interactuar» con otros elementos wiki de la página. Por ejemplo, la salida de una función de análisis se podría usar como parámetro de una plantilla o en la construcción de un enlace.

La sintaxis típica de una función de análisis es:

{{ #functionname: param1 | param2 | param3 }}

Para más información, consulta la documentación de Parser::setFunctionHook ( $id, $callback, $flags = 0 ). Según esta documentación,

The callback function should have the form:
function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }
O con SFH_OBJECT_ARGS:
function myParserFunction( $parser, $frame, $args ) { ... }

The first variant of the call passes all arguments as plain text. The second passes all arguments as an array of PPNode s, except for the first ($args[0]), which is currently text, though this may change in the future. These represent the unexpanded wikitext. The $frame parameter can be used to expand these arguments as needed. This is commonly used for conditional processing so that only the "true" case is evaluated with an if- or switch-like parser function. The frame object can also climb up the document tree to get information about the caller and has functions to determine and manage call depth, time-to-live, and whether the result of the parser function is volatile.

Crear una función de análisis es ligeramente más complejo que crear una nueva etiqueta porque el nombre de la función debe ser una palabra mágica, una palabra clave que sea compatible con el uso de alias y localización.

Ejemplo simple

A continuación hay un ejemplo de una extensión que crea una función de análisis.

El registro va a extension.json y el código a includes/ExampleExtension.php, respectivamente:

{
	"name": "ExampleExtension",
	"author": "Me",
	"version": "1.0.0",
	"url": "https://www.mediawiki.org/wiki/Extension:ExampleExtension",
	"descriptionmsg": "exampleextension-desc",
	"license-name": "GPL-2.0-or-later",
	"type": "parserhook",
	"MessagesDirs": {
		"ExampleExtension": [
			"i18n"
		]
	},
	"AutoloadClasses": {
		"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
	},
	"ExtensionMessagesFiles": {
		"ExampleExtensionMagic": "ExampleExtension.i18n.php"
	},
	"Hooks": {
		"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
	},
	"manifest_version": 1
}
<?php
class ExampleExtensionHooks {
   // Register any render callbacks with the parser
   public static function onParserFirstCallInit( Parser $parser ) {

      // Create a function hook associating the "example" magic word with renderExample()
      $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
   }

   // Muestra la salida de {{#example:}}.
   public static function renderExample( Parser $parser, $param1 = '', $param2 = '', $param3 = '' ) {

      // Los parámetros de entrada son wikitexto con las plantillas expandidas.
      // La salida también debería estar en forma de wikitexto.
      $output = "param1 is $param1 and param2 is $param2 and param3 is $param3";

      return $output;
   }
}

Otro archivo, ExampleExtension.i18n.php, en el directorio de tu extensión (no en el subdirectorio de src/) deberá contener:

<?php
/**
 * @license GPL-2.0-or-later
 * @author Your Name (YourUserName)
 */

$magicWords = [];

/** English
 * @author Your Name (YourUserName)
 */
$magicWords['en'] = [
   'example' => [ 0, 'example' ],
];

Con esta extensión activada,

  • {{#example: hello | hi | hey}}

produce:

  • param1 is hello and param2 is hi and param3 is hey
Este arreglo magicWords no es opcional. Si se omite, la función de análisis sencillamente no funcionará; el {{#example: hello | hi}} se mostrará como si la extensión no estuviera instalada. If only the language-specific array is initialized and not the magicWords array itself, this can cause localization errors as translations from other extensions leak into yours. You can associate magic words inline in PHP rather than through a i18n file. This is useful when defining hooks in LocalSettings.php
MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['MAG_CUSTOM', 'custom'];

Within LocalSettings.php

Magic words and their handling parser functions can be defined entirely in LocalSettings.php.

$wgHooks['ParserFirstCallInit'][] = function ( Parser $parser ) 
{
	MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['wikicodeToHtml', 'wikicodeToHtml'];

	$parser->setFunctionHook( 'wikicodeToHtml', 'wikicodeToHtml' );
};
 
function wikicodeToHtml( Parser $parser, $code = '' ) 
{
	$title = $parser->getTitle();
	$options = $parser->Options();
	$options->enableLimitReport(false);
	$parser = $parser->getFreshParser();
	return [$parser->parse($code, $title, $options)->getText(), 'isHTML' => true];
}

Funciones más largas

For longer functions, you may want to split the hook functions out to a _body.php or .hooks.php file and make them static functions of a class. Then you can load the class with $wgAutoloadClasses and call the static functions in the hooks; e.g.:

Agrega esto en tu archivo extension.json:

"Hooks": {
	"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
},
"AutoloadClasses": {
	"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
}

Luego agrega esto en tu archivo src/ExampleExtensionHooks.php:

class ExampleExtensionHooks {
      public static function onParserFirstCallInit( Parser $parser ) {
           $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
      }
}

Interfaz del analizador

Control del análisis sintáctico de la salida

Para que el wikitexto devuelto por tu función de análisis esté completamente analizado (incluyendo las expansiones de plantillas), define la opción noparse como falsa en la salida.

return [ $output, 'noparse' => false ];

Parece ser que el valor predeterminado para noparse cambió de falso a verdadero, al menos en algunos casos, en algún momento en torno a la versión 1.12.

En cambio, para que tu función de análisis devuelva HTML no analizado, en lugar de wikitexto, usa lo siguiente:

return [ $output, 'noparse' => true, 'isHTML' => true ];

Nombramiento

Por defecto, MW añade una almohadilla («#») al nombre de cada función de análisis. Para suprimir este añadido (y obtener una función de análisis sin el prefijo «#»), debes incluir la constante SFH_NO_HASH en el argumento opcional de banderas en setFunctionHook, como se describe más adelante. To suppress that addition (and obtain a parser function with no "#" prefix), include the SFH_NO_HASH constant in the optional flags argument to setFunctionHook, as described below.

Al elegir un nombre sin almohadilla prefijada, ten en cuenta que ya no es posible transcluir una página con un nombre que empiece por ese nombre de función seguido del carácter dos puntos. En particular, evita nombres de función iguales al nombre de un espacio de nombres. En caso de que la transclusión interwiki [1] esté habilitada, también debes evitar los nombres de función iguales a un prefijo interwiki.

The setFunctionHook hook

Para más información sobre la interfaz del analizador, consulta la documentación de setFunctionHook en includes/Parser.php. Aquí se muestra una copia (posiblemente obsoleta) de estos comentarios:

function setFunctionHook( $id, $callback, $flags = 0 )

Parámetros:

  • string $id - el identificador de la palabra mágica
  • mixed $callback - The callback function (and object) to use
  • integer $flags - Optional. Set it to the SFH_NO_HASH (1) constant to call the function without "#".

Set it to SFH_OBJECT_ARGS (2) to pass a PPFrame object and array of arguments instead of a series of function arguments, for which see above. Defaults to 0 (no flags).

Return value: The old callback function for this name, if any

Create a function, e.g., {{#sum:1|2|3}}. The callback function should have the form:

function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }

The callback may either return the text result of the function, or an array with the text in element 0, and a number of flags in the other elements. The names of the flags are specified in the keys. Valid flags are:

Name Type Default Description
found Boolean true El texto devuelto es válido, deja de procesar la plantilla. Esto está activado por defecto.
text ? ? The text to return from the function. If isChildObj or isLocalObj are specified, this should be a DOM node instead.
noparse Boolean true Las etiquetas HTML inseguras no se deben suprimir, etc.
isHTML Boolean ? El valor devuelto está en HTML, protégelo contra transformaciones a wikitexto But see discussion
nowiki Boolean usually false El marcado wiki en el valor de retorno debe escaparse
isChildObj Boolean ? true if the text is a DOM node needing expansion in a child frame.
isLocalObj Boolean ? true if he text is a DOM node needing expansion in the current frame. The default value depends on other values and outcomes.
preprocessFlags ? false Optional PPFrame flags to use when parsing the returned text. This only applies when noparse is false.
title ? false The Title object where the text came from.
forceRawInterwiki Boolean ? true if interwiki transclusion must be forced to be done in raw mode and not rendered.


Expensive parser functions

Some parser functions represent a significant use of a wiki's resources and should be marked as "expensive". The number of expensive parser functions on any given page is limited by the $wgExpensiveParserFunctionLimit setting. What counts as expensive is left up to the function itself, but typically, anything that is likely to cause a delay that extends beyond simple processing of data should be considered. This includes things like database reads and writes, launching a shell script synchronously, or file manipulation. On the other hand, not all such functions should necessarily be tagged. Semantic MediaWiki, for example, only marks a percentage of its database reads as expensive. This is due to the fact that on certain data-intensive pages, it could easily overflow the normal expensive parser function limits. In cases like this, the potential for noticeably slower performance that doesn't get flagged as expensive is a trade-off to having the functionality that SMW offers.

To mark your parser function as expensive, from within the body of the function's code, use $result = $parser->incrementExpensiveFunctionCount();. The return value will be false if the expensive function limit has been reached or exceeded.

Parámetros nombrados

Las funciones de análisis no permiten el uso de parámetros nombrados de la manera en que lo hacen las plantillas y extensiones de marcado, pero a veces puede ser útil imitarlos. Los usuarios a menudo están acostumbrados a usar barras verticales ( | ) para separar argumentos, así que está bien poder hacerlo también en el contexto de las funciones de análisis. He aquí un ejemplo sencillo de cómo conseguirlo:

function ExampleExtensionRenderParserFunction( &$parser ) {
	// Suppose the user invoked the parser function like so:
	// {{#myparserfunction: foo=bar | apple=orange | banana }}

	$options = extractOptions( array_slice( func_get_args(), 1 ) );

	// Now you've got an array that looks like this:
	// [foo] => 'bar'
	// [apple] => 'orange'
	// [banana] => true
	// Continue writing your code...
}

/**
 * Converts an array of values in form [0] => "name=value"
 * into a real associative array in form [name] => value
 * If no = is provided, true is assumed like this: [name] => true
 *
 * @param array string $options
 * @return array $results
 */
function extractOptions( array $options ) {
	$results = [];
	foreach ( $options as $option ) {
		$pair = array_map( 'trim', explode( '=', $option, 2 ) );
		if ( count( $pair ) === 2 ) {
			$results[ $pair[0] ] = $pair[1];
		}
		if ( count( $pair ) === 1 ) {
			$results[ $pair[0] ] = true;
		}
	}
	return $results;
}

Véase también

General and related guides:

Code:

  • The Parser Hooks PHP library, which provides an object orientated interface for declarative parser hooks

Examples: