wiki.techinc.nl/tests/phpunit/unit/includes/HtmlHelperTest.php
Gergő Tisza 2557f96cb7
Add HtmlHelper::modifyElements() for small HTML modifications
Adds HtmlHelper, which is intended to be a static utility class
for doing simple modifications to HTML strings in a safe way,
without exposing the caller to the complex Remex interface.
Currently only has one method, which is mainly useful for
modifying element attributes.

The code is largely based on the Wikibase FormatEntities class.

Bug: T217850
Change-Id: I45db9e61e47eb69df32a167d9d1dd146a8719676
2022-05-08 15:55:00 +02:00

44 lines
1.5 KiB
PHP

<?php
namespace MediaWiki\Tests\Unit;
use MediaWiki\HtmlHelper;
use MediaWikiUnitTestCase;
use Wikimedia\RemexHtml\HTMLData;
use Wikimedia\RemexHtml\Serializer\SerializerNode;
use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
class HtmlHelperTest extends MediaWikiUnitTestCase {
/**
* @covers \MediaWiki\HtmlHelper::modifyElements
*/
public function testModifyElements() {
$shouldModifyCallback = static function ( SerializerNode $node ) {
return $node->namespace === HTMLData::NS_HTML
&& $node->name === 'a'
&& isset( $node->attrs['href'] );
};
$modifyCallbackInPlace = static function ( SerializerNode $node ) {
$node->attrs['href'] = 'https://tracker.org/' . $node->attrs['href'];
return $node;
};
$input = '<p>Foo <a href="https://example.org/">bar</a> baz</p>';
$expectedOutput = '<p>Foo <a href="https://tracker.org/https://example.org/">bar</a> baz</p>';
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace );
$this->assertSame( $expectedOutput, $output );
$modifyCallbackNew = static function ( SerializerNode $node ) {
$href = 'https://tracker.org/' . $node->attrs['href'];
$newNode = new SerializerNode( $node->id, $node->parentId, $node->namespace, $node->name,
new PlainAttributes( [ 'href' => $href ] ), $node->void );
$node->attrs['href'] = 'https://tracker.org/' . $node->attrs['href'];
return $newNode;
};
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackNew );
$this->assertSame( $expectedOutput, $output );
}
}