File: HtmlHelperTest.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (59 lines) | stat: -rw-r--r-- 2,376 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

namespace MediaWiki\Tests\Unit;

use MediaWiki\Html\HtmlHelper;
use MediaWikiUnitTestCase;
use Wikimedia\RemexHtml\HTMLData;
use Wikimedia\RemexHtml\Serializer\SerializerNode;
use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;

/**
 * @covers \MediaWiki\Html\HtmlHelper
 */
class HtmlHelperTest extends MediaWikiUnitTestCase {

	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 );

		// Check the "legacy compatibility" mode, for void elements like <link>
		$input = "<link data-test='<style data-mw-deduplicate=\"&nbsp;\"&gt;bar</style&gt;'>";
		$shouldModifyCallback = static function ( SerializerNode $node ) {
			return false;
		};
		// HTML5 output
		$expectedOutput = '<link data-test="<style data-mw-deduplicate=&quot;&nbsp;&quot;>bar</style>">';
		$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace, true );
		$this->assertSame( $expectedOutput, $output );

		// "Legacy" output
		$expectedOutput = '<link data-test="<style data-mw-deduplicate=&quot;&#160;&quot;&gt;bar</style&gt;" />';
		$output = HtmlHelper::modifyElements( $input, $shouldModifyCallback, $modifyCallbackInPlace, false );
		$this->assertSame( $expectedOutput, $output );
	}

}