Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.50% covered (warning)
87.50%
7 / 8
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
NativeLazyImageTransform
87.50% covered (warning)
87.50%
7 / 8
50.00% covered (danger)
50.00%
1 / 2
6.07
0.00% covered (danger)
0.00%
0 / 1
 apply
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 doRewriteImagesForLazyLoading
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
1<?php
2
3namespace MobileFrontend\Transforms;
4
5use Wikimedia\Parsoid\DOM\Document;
6use Wikimedia\Parsoid\DOM\Element;
7use Wikimedia\Parsoid\Utils\DOMCompat;
8
9/**
10 * Transforms Parsoid content so that it works with lazy loaded images.
11 */
12class NativeLazyImageTransform implements IMobileTransform {
13
14    /**
15     * @param Element $node to be transformed
16     */
17    public function apply( Element $node ) {
18        // Parsoid can have nested sections, so we use a child combinator
19        // here to avoid multiple applications of the lazy image transform to the
20        // nested sections.
21        $sections = DOMCompat::querySelectorAll( $node, '.mw-parser-output > section' );
22        foreach ( $sections as $sectionNumber => $section ) {
23            if ( $sectionNumber > 0 ) {
24                $this->doRewriteImagesForLazyLoading( $section, $section->ownerDocument );
25            }
26        }
27    }
28
29    /**
30     * Enables images to be loaded asynchronously
31     *
32     * @param Element|Document $el Element or document to rewrite images in.
33     * @param ?Document $doc Document to create elements in
34     */
35    private function doRewriteImagesForLazyLoading( $el, ?Document $doc ) {
36        if ( $doc === null ) {
37            return;
38        }
39
40        foreach ( DOMCompat::querySelectorAll( $el, 'img' ) as $img ) {
41            $img->setAttribute( 'loading', 'lazy' );
42        }
43    }
44}