Debian Codegraph @

includes/OutputTransform/Stages/DeduplicateStyles.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\OutputTransform\Stages;
4
5 use MediaWiki\Html\HtmlHelper;
6 use MediaWiki\OutputTransform\ContentTextTransformStage;
7 use MediaWiki\Parser\ParserOptions;
8 use MediaWiki\Parser\ParserOutput;
9 use Wikimedia\RemexHtml\Serializer\SerializerNode;
10 use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
11
12 /**
13 * Generates a list of unique style links
14 * @internal
15 */
16 class DeduplicateStyles extends ContentTextTransformStage {
17
18 public function shouldRun( ParserOutput $po, ?ParserOptions $popts, array $options = [] ): bool {
19 return $options['deduplicateStyles'] ?? true;
20 }
21
22 protected function transformText( string $text, ParserOutput $po, ?ParserOptions $popts, array &$options ): string {
23 $seen = [];
24 $isParsoidContent = $options['isParsoidContent'] ?? false;
25
26 $transform = static function ( $fragment ) use ( &$seen, $isParsoidContent ) {
27 return HtmlHelper::modifyElements(
28 $fragment,
29 static function ( SerializerNode $node ): bool {
30 return $node->name === 'style' &&
31 ( $node->attrs['data-mw-deduplicate'] ?? '' ) !== '';
32 },
33 static function ( SerializerNode $node ) use ( &$seen ): SerializerNode {
34 $key = $node->attrs['data-mw-deduplicate'];
35 if ( !isset( $seen[$key] ) ) {
36 $seen[$key] = true;
37 return $node;
38 }
39 // We were going to use an empty <style> here, but there
40 // was concern that would be too much overhead for browsers.
41 // So let's hope a <link> with a non-standard rel and href isn't
42 // going to be misinterpreted or mangled by any subsequent processing.
43 $node->name = 'link';
44 $node->attrs = new PlainAttributes( [
45 'rel' => 'mw-deduplicated-inline-style',
46 'href' => "mw-data:" . wfUrlencode( $key ),
47 ] );
48 $node->children = [];
49 $node->void = true;
50 return $node;
51 },
52 $isParsoidContent
53 );
54 };
55
56 if ( !$isParsoidContent ) {
57 // Optimization: Only transform possible style nodes to avoid having to tokenize the entire output,
58 // which is expensive for large pages (T394059).
59 // This is unsafe to do for Parsoid content, since the naïve regex below might match encoded style
60 // tags within data-parsoid attribute values, so only apply it to legacy parser output.
61 // Parsoid content transformations will be further optimized in T394005.
62 return preg_replace_callback(
63 '#<style\s+([^>]*data-mw-deduplicate\s*=[\'"][^>]*)>.*?</style>#s',
64 static fn ( array $matches ) => $transform( $matches[0] ),
65 $text
66 );
67 }
68
69 return $transform( $text );
70 }
71 }