| 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 |
|
| 14 |
|
| 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 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 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 |
|
| 58 |
|
| 59 |
e |
| 60 |
|
| 61 |
|
| 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 |
} |