| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Tests\Unit; |
| 4 |
|
| 5 |
use MediaWiki\Html\HtmlHelper; |
| 6 |
use MediaWikiUnitTestCase; |
| 7 |
use Wikimedia\RemexHtml\HTMLData; |
| 8 |
use Wikimedia\RemexHtml\Serializer\SerializerNode; |
| 9 |
use Wikimedia\RemexHtml\Tokenizer\PlainAttributes; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
class HtmlHelperTest extends MediaWikiUnitTestCase { |
| 15 |
|
| 16 |
public function testModifyElements() { |
| 17 |
$shouldModifyCallback = static function ( SerializerNode $node ) { |
| 18 |
return $node->namespace === HTMLData::NS_HTML |
| 19 |
&& $node->name === 'a' |
| 20 |
&& isset( $node->attrs['href'] ); |
| 21 |
}; |
| 22 |
$modifyCallbackInPlace = static function ( SerializerNode $node ) { |
| 23 |
$node->attrs['href'] = 'https://tracker.org/' . $node->attrs['href']; |
| 24 |
return $node; |
| 25 |
}; |
| 26 |
$input = '<p>Foo <a href="https://example.org/">bar</a> baz</p>'; |
| 27 |
$expectedOutput = '<p>Foo <a href="https://tracker.org/https://example.org/">bar</a> baz</p>'; |
| 28 |
|
| 29 |
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace ); |
| 30 |
$this->assertSame( $expectedOutput, $output ); |
| 31 |
|
| 32 |
$modifyCallbackNew = static function ( SerializerNode $node ) { |
| 33 |
$href = 'https://tracker.org/' . $node->attrs['href']; |
| 34 |
$newNode = new SerializerNode( $node->id, $node->parentId, $node->namespace, $node->name, |
| 35 |
new PlainAttributes( [ 'href' => $href ] ), $node->void ); |
| 36 |
$node->attrs['href'] = 'https://tracker.org/' . $node->attrs['href']; |
| 37 |
return $newNode; |
| 38 |
}; |
| 39 |
|
| 40 |
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackNew ); |
| 41 |
$this->assertSame( $expectedOutput, $output ); |
| 42 |
|
| 43 |
|
| 44 |
$input = "<link data-test='<style data-mw-deduplicate=\" \">bar</style>'>"; |
| 45 |
$shouldModifyCallback = static function ( SerializerNode $node ) { |
| 46 |
return false; |
| 47 |
}; |
| 48 |
|
| 49 |
$expectedOutput = '<link data-test="<style data-mw-deduplicate=" ">bar</style>">'; |
| 50 |
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace, true ); |
| 51 |
$this->assertSame( $expectedOutput, $output ); |
| 52 |
|
| 53 |
|
| 54 |
$expectedOutput = '<link data-test="<style data-mw-deduplicate=" ">bar</style>" />'; |
| 55 |
$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace, false ); |
| 56 |
$this->assertSame( $expectedOutput, $output ); |
| 57 |
} |
| 58 |
|
| 59 |
} |