wiki.techinc.nl/includes/Html/HtmlHelperTrait.php
C. Scott Ananian a6739e066e Use Remex/HtmlHelper to implement Parser::replaceTableOfContents
This is more robust and secure than the regular expression previously
used to extract the <meta> tag.

We also improve HtmlHelper slightly be adding the ability to replace
an element with an 'outerHTML' string.

Because our output is being run through Remex, there is a slightly
larger degree of HTML normalization in the output than previously,
which is visible in some small tweaks to test case outputs.

Bug: T381617
Depends-On: I2712e0fa9272106e8cd686980f847ee7f6385b6f
Change-Id: I4cb2f29cf890af90f295624c586d9e1eb1939b95
(cherry picked from commit 7ebd8034b54495f28f4c5583d4fa55071634b593)
2025-09-29 22:01:08 +00:00

51 lines
1.4 KiB
PHP

<?php
namespace MediaWiki\Html;
use Wikimedia\Assert\Assert;
use Wikimedia\RemexHtml\Serializer\HtmlFormatter;
use Wikimedia\RemexHtml\Serializer\SerializerNode;
/**
* Internal helper trait for HtmlHelper::modifyHtml.
*
* This is designed to extend a HtmlFormatter.
*
* @phan-file-suppress PhanTraitParentReference
*/
trait HtmlHelperTrait {
/** @var callable */
private $shouldModifyCallback;
/** @var callable */
private $modifyCallback;
public function __construct( $options, callable $shouldModifyCallback, callable $modifyCallback ) {
parent::__construct( $options );
$this->shouldModifyCallback = $shouldModifyCallback;
$this->modifyCallback = $modifyCallback;
// Escape U+0338 (T387130)
'@phan-var HtmlFormatter $this';
$this->textEscapes["\u{0338}"] = '&#x338;';
}
public function element( SerializerNode $parent, SerializerNode $node, $contents ) {
if ( ( $this->shouldModifyCallback )( $node ) ) {
$node = clone $node;
$node->attrs = clone $node->attrs;
$newNode = ( $this->modifyCallback )( $node );
Assert::parameterType( [ SerializerNode::class, 'string' ], $newNode, 'return value' );
if ( is_string( $newNode ) ) {
// Replace this element with an "outerHTML" string.
return $newNode;
}
return parent::element( $parent, $newNode, $contents );
} else {
return parent::element( $parent, $node, $contents );
}
}
public function startDocument( $fragmentNamespace, $fragmentName ) {
return '';
}
}