Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
DedupeStyles
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 1
 dedupe
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\PP\Handlers;
5
6use Wikimedia\Parsoid\Config\Env;
7use Wikimedia\Parsoid\DOM\Element;
8use Wikimedia\Parsoid\Utils\DOMCompat;
9use Wikimedia\Parsoid\Utils\DOMDataUtils;
10use Wikimedia\Parsoid\Utils\DOMUtils;
11use Wikimedia\Parsoid\Utils\DTState;
12
13class DedupeStyles {
14
15    /**
16     * @param Element $node
17     * @param Env $env
18     * @param DTState $state
19     * @return bool|Element
20     */
21    public static function dedupe( Element $node, Env $env, DTState $state ) {
22        // Don't run on embedded docs for now since we don't want the
23        // canonical styles to be introduced in embedded HTML which means
24        // they will get lost wrt the top level document.
25        if ( !$state->atTopLevel ) {
26            return true;
27        }
28
29        $key = DOMCompat::getAttribute( $node, 'data-mw-deduplicate' );
30        if ( $key === null ) {
31            // Not a templatestyles <style> tag
32            return true;
33        }
34
35        if ( !isset( $env->styleTagKeys[$key] ) ) {
36            // Not a dupe
37            $env->styleTagKeys[$key] = true;
38            return true;
39        }
40
41        if ( !DOMUtils::isFosterablePosition( $node ) ) {
42            // Dupe - replace with a placeholder <link> reference
43            $link = $node->ownerDocument->createElement( 'link' );
44            DOMUtils::addRel( $link, 'mw-deduplicated-inline-style' );
45            $link->setAttribute( 'href', 'mw-data:' . $key );
46            $link->setAttribute( 'about', DOMCompat::getAttribute( $node, 'about' ) ?? '' );
47            $link->setAttribute( 'typeof', DOMCompat::getAttribute( $node, 'typeof' ) ?? '' );
48            DOMDataUtils::setDataParsoid( $link, DOMDataUtils::getDataParsoid( $node ) );
49            DOMDataUtils::setDataMw( $link, DOMDataUtils::getDataMw( $node ) );
50            $node->parentNode->replaceChild( $link, $node );
51            return $link;
52        } else {
53            $env->log( 'info/wt2html/templatestyle',
54                'Duplicate style tag found in fosterable position. ' .
55                    'Not deduping it, but emptying out the style tag for performance reasons.'
56            );
57            DOMCompat::replaceChildren( $node );
58            return true;
59        }
60    }
61}