Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
MobileFormatter
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
4 / 4
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 applyTransforms
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getHtml
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 canApply
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3use MobileFrontend\Transforms\IMobileTransform;
4use Wikimedia\Parsoid\Core\DOMCompat;
5use Wikimedia\Parsoid\DOM\Element;
6use Wikimedia\Parsoid\Ext\DOMUtils;
7use Wikimedia\Parsoid\Wt2Html\XHtmlSerializer;
8
9/**
10 * Converts HTML into a mobile-friendly version
11 */
12class MobileFormatter {
13
14    /** @var Element */
15    private $body;
16
17    /**
18     * @inheritDoc
19     */
20    public function __construct( string $html ) {
21        $doc = DOMUtils::parseHTML( $html );
22        $this->body = DOMCompat::getBody( $doc );
23    }
24
25    /**
26     * Performs various transformations to the content to make it appropriate for mobile devices.
27     *
28     * @param array<IMobileTransform> $transforms lit of transforms to be sequentually applied
29     *   to html DOM
30     */
31    public function applyTransforms( array $transforms ): void {
32        foreach ( $transforms as $transform ) {
33            $transform->apply( $this->body );
34        }
35    }
36
37    /**
38     * Get the serialized HTML
39     *
40     * @return string
41     */
42    public function getHtml(): string {
43        // Like DOMCompat::getInnerHTML(), but disable 'smartQuote' for compatibility with
44        // ParserOutput::EDITSECTION_REGEX matching 'mw:editsection' tags (T274709)
45        return XHtmlSerializer::serialize( $this->body, [ 'innerXML' => true, 'smartQuote' => false ] )['html'];
46    }
47
48    /**
49     * Check whether the MobileFormatter can be applied to the text of a page.
50     *
51     * @param array $options with 'maxHeadings' and 'maxImages' keys that limit the MobileFormatter
52     *  to pages with less than or equal to that number of headings and images.
53     * @return bool
54     */
55    public function canApply( array $options ): bool {
56        $headings = DOMCompat::querySelectorAll( $this->body, 'h1,h2,h3,h4,h5,h6' );
57        $images = DOMCompat::querySelectorAll( $this->body, 'img' );
58        return count( $headings ) <= $options['maxHeadings'] && count( $images ) <= $options['maxImages'];
59    }
60}