Manual:パーサー関数
MediaWiki 1.7で
説明
タグ
パーサー
{{ #functionname: param1 | param2 | param3 }}
Parser::setFunctionHook ( $id, $callback, $flags = 0 )
の
- コールバック
関数 の構文 は次 のとおりです。function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }
- あるいは
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.
パーサー
単純 な例
パーサー
{
"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 {
// レンダリング コールバックをパーサーに登録 します
public static function onParserFirstCallInit( Parser $parser ) {
// 関数 フックを作成 し、"example" マジックワードとrenderExample()を対応 させます
$parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
}
// {{#example:}}の出力 を表示 。
public static function renderExample( Parser $parser, $param1 = '', $param2 = '', $param3 = '' ) {
// 入力 パラメーターがウィキテキストでテンプレートを展開 します。
// 出力 もウィキテキストになります。
$output = "param1 is $param1 and param2 is $param2 and param3 is $param3";
return $output;
}
}
<?php
/**
* @license GPL-2.0-or-later
* @author Your Name (YourUserName)
*/
$magicWords = [];
/** English
* @author Your Name (YourUserName)
*/
$magicWords['en'] = [
'example' => [ 0, 'example' ],
];
この
- {{#example: hello | hi | hey}}
- param1 is hello and param2 is hi and param3 is hey
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];
}
より長 い関数
より
extension.json
ファイルに
"Hooks": {
"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
},
"AutoloadClasses": {
"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
}
- その
他 の様式 はイベントハンドラの記述 を参照 してください。
src/ExampleExtensionHooks.php
ファイルに
class ExampleExtensionHooks {
public static function onParserFirstCallInit( Parser $parser ) {
$parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
}
}
パーサー インターフェイス
出力 の構文 解析 の制御
noparse
オプションに false を
return [ $output, 'noparse' => false ];
noparse
の
return [ $output, 'noparse' => true, 'isHTML' => true ];
命名
MW は
もしハッシュ
setFunctionHook フック
パーサーに
function setFunctionHook( $id, $callback, $flags = 0 )
パラメーター:
- string $id - マジックワード ID
- mixed $callback -
使用 するコールバック関数 (とオブジェクト)
- integer $flags - (
省略 可能 )関数 を「#」なしで呼 び出 すようにするには、SFH_NO_HASH定数 を設定 します。
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).
たとえば{{#sum:1|2|3}}
など
function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }
コールバックの
Name | Type | Default | Description |
---|---|---|---|
found | Boolean | true
|
|
text | ? | ? | The text to return from the function. If isChildObj or isLocalObj are specified, this should be a DOM node instead. |
noparse | Boolean | true
|
true if text should not be preprocessed to a DOM tree, e.g. unsafe HTML tags should not be stripped, etc.
|
isHTML | Boolean | ? | |
nowiki | Boolean | usually false
|
true if wiki markup in the return value (text) should be escaped.
|
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.
名前 付 きパラメーター
パーサー
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;
}
関連 項目
General and related guides:
- Manual:
拡張 機能 の開発 , or for more general information about extensions, see Manual:拡張 機能 and拡張 機能 のよくある質問 . - Manual:タグ
拡張 機能 - Manual:マジックワード
Code:
- Manual:Parser.php
- Manual:フック/ParserFirstCallInit
- Parser function hooks - an (incomplete) list of parser functions provided by core and extensions
- パーサー フック PHP ライブラリ -
宣言 型 パーサーフックのためのオブジェクト指向 インターフェイスを提供 する - Manual:Extension data
Examples:
- ParserFunctions
拡張 機能 は、よく知 られたパーサー関数 のコレクションです。 - Help:Extension:ParserFunctions
- Category:Parser function extensions