Jump to content

Manual:Parser.php/pt: Difference between revisions

From mediawiki.org
Content deleted Content added
Created page with "Obter a linguagem de destino para o conteúdo que está a ser analisado."
FuzzyBot (talk | contribs)
Updating to match new version of source page
 
(21 intermediate revisions by 2 users not shown)
Line 19: Line 19:
=== Como criar uma nova instância Parser ===
=== Como criar uma nova instância Parser ===
Se não tem acesso, pode criar uma nova instância utilizando {{class|ParserFactory}} e chamando o seu método <code>create</code>.<ref>
Se não tem acesso, pode criar uma nova instância utilizando {{class|ParserFactory}} e chamando o seu método <code>create</code>.<ref>
<span lang="en" dir="ltr" class="mw-content-ltr">Prior to MediaWiki 1.36, it was still possible to construct a Parser class directly.</span>
Antes do MediaWiki 1.36, ainda era possível criar uma classe "Parser" diretamente.
</ref>
</ref>
O construtor de ParserFactory utiliza vários argumentos.
<span lang="en" dir="ltr" class="mw-content-ltr">The constructor of the ParserFactory takes several arguments.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">To create a ParserFactory with default options, use <code>MediaWikiServices::getInstance()->getParserFactory()</code>.</span>
Para criar um ParserFactory com as opções predefinidas, utilize <code>MediaWikiServices::getInstance()->getParserFactory()</code>.


One-liner para obter uma nova instância de Parser:
<span lang="en" dir="ltr" class="mw-content-ltr">One-liner for getting a new Parser instance:</span>


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 30: Line 30:
</syntaxhighlight>
</syntaxhighlight>


Esta nova instância ainda não está pronta para utilização.
<span lang="en" dir="ltr" class="mw-content-ltr">This new instance is not ready for use yet.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">The next step is to set ParserOptions.</span>
O próximo passo é definir ParserOptions.


<div lang="en" dir="ltr" class="mw-content-ltr">
=== How to get the main Parser instance ===
=== How to get the main Parser instance ===
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
One-liner for getting the main Parser instance, though unsafe when the caller is not in a top-level context:
One-liner for getting the main Parser instance, though unsafe when the caller is not in a top-level context:
</div>


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 70: Line 75:
=== [[Special:MyLanguage/Manual:Hooks|Hooks]] ===
=== [[Special:MyLanguage/Manual:Hooks|Hooks]] ===


Os seguintes ''hooks'' são disponibilizados em vários estágios do ciclo de análise:
<div lang="en" dir="ltr" class="mw-content-ltr">
The following hooks are made available at various stages in the parsing cycle:
</div>


{| class="wikitable" cellpadding="5" border="1"
{| class="wikitable" cellpadding="5" border="1"
Line 97: Line 100:
| <span lang="en" dir="ltr" class="mw-content-ltr">Used to process the expanded wiki code after &lt;nowiki>, HTML-comments, and templates have been treated.</span>
| <span lang="en" dir="ltr" class="mw-content-ltr">Used to process the expanded wiki code after &lt;nowiki>, HTML-comments, and templates have been treated.</span>
|-
|-
| 1.10.1 || {{ll|Manual:Hooks/BeforeParserFetchTemplateAndtitle|BeforeParserFetchTemplateAndtitle}}
| 1.36.0 || {{ll|Manual:Hooks/BeforeParserFetchTemplateRevisionRecord|BeforeParserFetchTemplateRevisionRecord}}
| <span lang="en" dir="ltr" class="mw-content-ltr">Allows an extension to specify a version of a page to get for inclusion in a template.</span>
| <span lang="en" dir="ltr" class="mw-content-ltr">Allows an extension to specify a version of a page to get for inclusion in a template.</span>
|-
| 1.10.1 || {{ll|Manual:Hooks/BeforeParserrenderImageGallery|BeforeParserrenderImageGallery}}
| <span lang="en" dir="ltr" class="mw-content-ltr">Allows an extension to modify an image gallery before it is rendered.</span>
|-
|-
| 1.12.0 || {{ll|Manual:Hooks/ParserFirstCallInit|ParserFirstCallInit}}
| 1.12.0 || {{ll|Manual:Hooks/ParserFirstCallInit|ParserFirstCallInit}}
Line 111: Line 111:
| 1.18.0 || {{ll|Manual:Hooks/BeforeParserFetchFileAndTitle|BeforeParserFetchFileAndTitle}}
| 1.18.0 || {{ll|Manual:Hooks/BeforeParserFetchFileAndTitle|BeforeParserFetchFileAndTitle}}
| <span lang="en" dir="ltr" class="mw-content-ltr">Before an image is rendered by Parser.</span>
| <span lang="en" dir="ltr" class="mw-content-ltr">Before an image is rendered by Parser.</span>
|-
| 1.19.0 || {{ll|Manual:Hooks/ParserSectionCreate|ParserSectionCreate}}
| <span lang="en" dir="ltr" class="mw-content-ltr">Called each time the parser creates a document section from wikitext.</span>
|-
|-
| 1.22.0 || {{ll|Manual:Hooks/ParserLimitReportFormat|ParserLimitReportFormat}}
| 1.22.0 || {{ll|Manual:Hooks/ParserLimitReportFormat|ParserLimitReportFormat}}
Line 124: Line 121:
| Replacement for deprecated BeforeParserFetchTemplateAndtitle
| Replacement for deprecated BeforeParserFetchTemplateAndtitle
|}
|}



<span id="Other_methods"></span>
<span id="Other_methods"></span>
Line 141: Line 139:
*<code>getTags ()</code> Assessor.
*<code>getTags ()</code> Assessor.
*<code>getTargetLanguage ()</code> Obter a linguagem de destino para o conteúdo que está a ser analisado.
*<code>getTargetLanguage ()</code> Obter a linguagem de destino para o conteúdo que está a ser analisado.
*<code>getTitle ()</code> <span lang="en" dir="ltr" class="mw-content-ltr">Accessor for the {{ll|Manual:Title.php|Title}} object.</span>
*<code>getTitle ()</code> Assessor para o objeto {{ll|Manual:Title.php|Title}}.
*<code>getUser ()</code> <span lang="en" dir="ltr" class="mw-content-ltr">Get a {{ll|Manual:User.php|User}} object either from $this->mUser, if set, or from the ParserOptions object otherwise.</span>
*<code>getUser ()</code> <span lang="en" dir="ltr" class="mw-content-ltr">Get a {{ll|Manual:User.php|User}} object either from $this->mUser, if set, or from the ParserOptions object otherwise.</span>


<span id="Set"></span>
<span id="Set"></span>
=== Definir ===
<div class="mw-translate-fuzzy">
*<code>Parser::setFunctionHook()</code> {{ll|Manual:Parser functions|Crie uma função do analisador}}, por exemplo, <code><nowiki>{{#expr: 1 + 1}}</nowiki></code> ou <code><nowiki>{{sum:1|2|3}}</nowiki></code>. <span lang="en" dir="ltr" class="mw-content-ltr">The callback function can have the form: <code>function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }</code>.</span>
== Definir ==
</div>
*<code>Parser::setFunctionHook()</code> <span lang="en" dir="ltr" class="mw-content-ltr">{{ll|Manual:Parser functions|Create a parser function}}, e.g. <code><nowiki>{{#expr: 1 + 1}}</nowiki></code> or <code><nowiki>{{sum:1|2|3}}</nowiki></code>.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The callback function can have the form: <code>function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }</code>.</span>
*<code>Parser::setHook()</code> <span lang="en" dir="ltr" class="mw-content-ltr">{{ll|Manual:Tag extensions|Create an HTML-style tag}}, e.g. {{tmpl|0={{tag|yourtag|content=$1}}|special text}}.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The callback should have the following form: {{phpi|function myParserHook( $text, $params, $parser, $frame ) { ... }}}</span>
*<code>Parser::setHook()</code> <span lang="en" dir="ltr" class="mw-content-ltr">{{ll|Manual:Tag extensions|Create an HTML-style tag}}, e.g. {{tmpl|0={{tag|yourtag|content=$1}}|special text}}.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The callback should have the following form: {{phpi|function myParserHook( $text, $params, $parser, $frame ) { ... }}}</span>


<span id="Dynamic_properties"></span>
<div lang="en" dir="ltr" class="mw-content-ltr">
== Dynamic properties ==
=== Propriedades dinâmicas ===
</div>
<span lang="en" dir="ltr" class="mw-content-ltr">Do not add class properties to the Parser that have not been declared by the Parser.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">Do not add class properties to the Parser that have not been declared by the Parser.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">Exceptions aside, dynamic properties are deprecated in PHP 8.2 and they may not sit well with the shift to parallellised envisaged for {{ll|Parsoid}}.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">Exceptions aside, dynamic properties are deprecated in PHP 8.2 and they may not sit well with the shift to parallellised envisaged for {{ll|Parsoid}}.</span>
Line 159: Line 154:


<span id="See_also"></span>
<span id="See_also"></span>
== Ver também ==
== Consultar também ==
* {{ll|Manual:Code}} – <span lang="en" dir="ltr" class="mw-content-ltr">Overview of the key files and directories in the MediaWiki source code</span>
* {{ll|Manual:Code}} – Visão geral dos principais ficheiros e diretorias no código fonte do MediaWiki
* {{ll|Manual:ParserOptions.php}}
* {{ll|Manual:ParserOptions.php}}
* {{ll|Manual:PPFrame.php}} - <span lang="en" dir="ltr" class="mw-content-ltr">expansion frame interface</span>
* {{ll|Manual:PPFrame.php}} - Interface de quadro de expansão


<span id="External_links"></span>
<span id="External_links"></span>
== Hiperligações externas ==
== Hiperligações externas ==
* ''[https://web.archive.org/web/20110709125138/http://musialek.org/?p=94 <span class="mw-translate-fuzzy">*[$uncovered ''A analisador da MediaWiki, revelado '']</span>]''
* ''[https://web.archive.org/web/20110709125138/http://musialek.org/?p=94 O MediaWiki parser, revelado]''


<span id="Breaking_changes"></span>
<div lang="en" dir="ltr" class="mw-content-ltr">
== Breaking changes ==
== Mudanças ==
</div>
* This class is namespaced (MediaWiki\Parser\Parser) since MW 1.42.
* This class is namespaced (MediaWiki\Parser\Parser) since MW 1.42.


<span id="References"></span>
<div lang="en" dir="ltr" class="mw-content-ltr">
== References ==
== Referências ==
</div>


[[Category:Parser{{#translation:}}| ]]
[[Category:Parser{{#translation:}}| ]]

Latest revision as of 05:16, 22 July 2026

Descrição

Este ficheiro contém a classe Parser, que contém o método parse, que converte o texto wiki em html.

Obter o Parser

Em muitos contextos, como quando cria uma função do analisador ou página especial, deveria ter acesso a uma instância de Parser.

Como criar uma nova instância Parser

Se não tem acesso, pode criar uma nova instância utilizando ParserFactory e chamando o seu método create.[1] O construtor de ParserFactory utiliza vários argumentos. Para criar um ParserFactory com as opções predefinidas, utilize MediaWikiServices::getInstance()->getParserFactory().

One-liner para obter uma nova instância de Parser:

$localParser = MediaWikiServices::getInstance()->getParserFactory()->create();

Esta nova instância ainda não está pronta para utilização. O próximo passo é definir ParserOptions.

How to get the main Parser instance

One-liner for getting the main Parser instance, though unsafe when the caller is not in a top-level context:

$localParser = MediaWikiServices::getInstance()->getParser();

O ciclo de analisar

  1. Call helper function Parser::internalParse(), which in turns calls
    1. Parser::replaceVariables, which replaces magic variables, templates, and template arguments with the appropriate text.
      1. It calls Parser::preprocessToDom, which preprocesses some wikitext and returns the document tree.
      2. Next it creates a PPFrame object and calls its expand() method to do the actual template magic.
    2. Sanitizer::removeHTMLtags(), which cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
    3. Parser::handleTables, which handles and renders the wikitext for tables.
    4. Parser::handleDoubleUnderscore, which removes valid double-underscore items, like __NOTOC__, and records them in array $Parser->mDoubleUnderscores.
    5. Parser::handleHeadings, which parses and renders section headers.
    6. Parser::handleInternalLinks, which processes internal links ([[ ]]) and stores them in $Parser->mLinkHolders (a LinkHolderArray object),
    7. Parser::handleAllQuotes, which replaces single quotes with HTML markup (‎<i>, ‎<b>, etc).
    8. Parser::handleExternalLinks, which replaces and renders external links.
    9. Parser::handleMagicLinks, which replaces special strings like "ISBN xxx" and "RFC xxx" with magic external links.
    10. Parser::handleHeadings, qual:
      • auto numbers headings if that options is enabled,
      • adds an [edit] link to sections for users who have enabled the option and can edit the page,
      • adds a Table of contents on the top for users who have enabled the option, and
      • auto-anchors headings.
  2. Next, parse() calls Parser::doBlockLevels, which renders lists from lines starting with ':', '*', '#', etc.
  3. Parser::replaceLinkHolders is called, which calls LinkHolderArray::replace on $Parser->mLinkHolders to replace link placeholders with actual links, in the buffer Placeholders created in Skin::makeLinkObj()
  4. Next, the text is language converted (when applicable) using the convert method of the appropriate Language object.
  5. Parser::replaceTransparentTags used to be called, which replaced transparent tags with values which are provided by the callback functions in $Parser->mTransparentTagHooks. Transparent tag hooks are like regular XML-style tag hooks, except they operate late in the transformation sequence, on HTML instead of wikitext.
  6. Sanitizer::normalizeCharReferences is called, which ensures that any entities and character references are legal for XML and XHTML specifically.
  7. If HTML tidy is enabled, MWTidy::tidy is called to do the tidying.
  8. Finally the rendered HTML result of the parse process is stored in the ParserOutput object $Parser->mOutput, which is returned to the caller of Parser::parse.

Os seguintes hooks são disponibilizados em vários estágios do ciclo de análise:

Versão Hook Descrição
1.5.0 ParserAfterTidy Used to add some final processing to the fully-rendered page output.
1.6.0 ParserBeforeInternalParse
1.6.0 ParserClearState Called at the end of Parser::clearState().
1.6.0 ParserGetVariableValueSwitch Assigns a value to a user defined variable.
1.6.0 ParserGetVariableValueTs Used to change the value of the time for the {{LOCAL...}} magic word.
1.6.0 ParserTestParser Called when creating a new instance of Parser for parser tests.
1.10.0 InternalParseBeforeLinks Used to process the expanded wiki code after <nowiki>, HTML-comments, and templates have been treated.
1.36.0 BeforeParserFetchTemplateRevisionRecord Allows an extension to specify a version of a page to get for inclusion in a template.
1.12.0 ParserFirstCallInit Called when the parser initialises for the first time.
1.12.0 ParserMakeImageParams Alter the parameters used to generate an image before it is generated.
1.18.0 BeforeParserFetchFileAndTitle Before an image is rendered by Parser.
1.22.0 ParserLimitReportFormat Replacement for deprecated ParserLimitReport
1.22.0 ParserLimitReportPrepare Replacement for deprecated ParserLimitReport
1.36.0 BeforeParserFetchTemplateRevisionRecord Replacement for deprecated BeforeParserFetchTemplateAndtitle


Outros métodos

Assessores

  • getCustomDefaultSort () Assessor para $mDefaultSort. Ao contrário de getDefaultSort(), este irá devolver false se não for definido nenhum.
  • getDefaultSort () Assessor para $mDefaultSort. Utilizará a string vazia se não for definido nenhum.
  • getOptions () Obter o objeto ParserOptions .
  • getOutput () Obter o objeto ParserOutput .
  • getPreprocessor () Obter o objeto Preprocessor .
  • Relacionado com Manual:Revision .
    • getRevisionId () Get the ID of the revision we are parsing.
    • getRevisionTimestamp () Get the timestamp associated with the current revision, adjusted for the default server-local timestamp.
    • getRevisionUser () Get the name of the user that edited the last revision.
  • getTags () Assessor.
  • getTargetLanguage () Obter a linguagem de destino para o conteúdo que está a ser analisado.
  • getTitle () Assessor para o objeto Title .
  • getUser () Get a User object either from $this->mUser, if set, or from the ParserOptions object otherwise.

Definir

  • Parser::setFunctionHook() Crie uma função do analisador , por exemplo, {{#expr: 1 + 1}} ou {{sum:1|2|3}}. The callback function can have the form: function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }.
  • Parser::setHook() Create an HTML-style tag , e.g. ‎<yourtag>special text‎</yourtag>. The callback should have the following form: function myParserHook( $text, $params, $parser, $frame ) { ...}

Propriedades dinâmicas

Do not add class properties to the Parser that have not been declared by the Parser. Exceptions aside, dynamic properties are deprecated in PHP 8.2 and they may not sit well with the shift to parallellised envisaged for Parsoid . If you are write an extension and need to store custom data in the Parser, see extension data for one possible way out.

Consultar também

Hiperligações externas

Mudanças

  • This class is namespaced (MediaWiki\Parser\Parser) since MW 1.42.

Referências

  1. Antes do MediaWiki 1.36, ainda era possível criar uma classe "Parser" diretamente.