MediaWiki REL1_39
HtmlHelper.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki;
4
5use Wikimedia\Assert\Assert;
6use Wikimedia\RemexHtml\HTMLData;
7use Wikimedia\RemexHtml\Serializer\HtmlFormatter;
8use Wikimedia\RemexHtml\Serializer\Serializer;
9use Wikimedia\RemexHtml\Serializer\SerializerNode;
10use Wikimedia\RemexHtml\Tokenizer\Tokenizer;
11use Wikimedia\RemexHtml\TreeBuilder\Dispatcher;
12use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder;
13
18
30 public static function modifyElements(
31 string $htmlFragment,
32 callable $shouldModifyCallback,
33 callable $modifyCallback
34 ) {
35 $formatter = new class( $options = [], $shouldModifyCallback, $modifyCallback ) extends HtmlFormatter {
37 private $shouldModifyCallback;
38
40 private $modifyCallback;
41
42 public function __construct( $options, $shouldModifyCallback, $modifyCallback ) {
43 parent::__construct( $options );
44 $this->shouldModifyCallback = $shouldModifyCallback;
45 $this->modifyCallback = $modifyCallback;
46 }
47
48 public function element( SerializerNode $parent, SerializerNode $node, $contents ) {
49 if ( ( $this->shouldModifyCallback )( $node ) ) {
50 $node = clone $node;
51 $node->attrs = clone $node->attrs;
52 $newNode = ( $this->modifyCallback )( $node );
53 Assert::parameterType( SerializerNode::class, $newNode, 'return value' );
54 return parent::element( $parent, $newNode, $contents );
55 } else {
56 return parent::element( $parent, $node, $contents );
57 }
58 }
59
60 public function startDocument( $fragmentNamespace, $fragmentName ) {
61 return '';
62 }
63 };
64 $serializer = new Serializer( $formatter );
65 $treeBuilder = new TreeBuilder( $serializer );
66 $dispatcher = new Dispatcher( $treeBuilder );
67 $tokenizer = new Tokenizer( $dispatcher, $htmlFragment );
68
69 $tokenizer->execute( [
70 'fragmentNamespace' => HTMLData::NS_HTML,
71 'fragmentName' => 'body',
72 ] );
73
74 return $serializer->getResult();
75 }
76
77}
Static utilities for manipulating HTML strings.
static modifyElements(string $htmlFragment, callable $shouldModifyCallback, callable $modifyCallback)
Modify elements of an HTML fragment via a user-provided callback.
A helper class for throttling authentication attempts.