Completed
Push — feature/anchors-twig-filter ( ee6739...2beb13 )
by Vladimir
02:22
created

HtmlUtils   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 88.89%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 45
ccs 16
cts 18
cp 0.8889
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A htmlXPath() 0 32 3
A normalizeHTML() 0 9 3
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Utilities;
9
10
abstract class HtmlUtils
11
{
12 17
    public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery)
13
    {
14 17
        $html = self::normalizeHTML($html);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $html. This often makes code more readable.
Loading history...
15
16 17
        libxml_use_internal_errors(true);
17
18 17
        $DOMDocument->loadHTML(
19 17
            mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'),
20 17
            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
21
        );
22
23 17
        $xmlErrors = libxml_get_errors();
24
25
        /** @var \LibXMLError $error */
26 17
        foreach ($xmlErrors as $error)
27
        {
28
            // Ignore errors about invalid tags
29
            //   http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors
30 1
            if ($error->code === 801)
31
            {
32
                continue;
33
            }
34
35 1
            @trigger_error($error->message, E_USER_WARNING);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
36
        }
37
38 17
        libxml_clear_errors();
39
40 17
        $xpath = new \DOMXPath($DOMDocument);
41
42 17
        return $xpath->query($xpathQuery);
43
    }
44
45 17
    private static function normalizeHTML($html)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
46
    {
47 17
        if (strpos($html, '<body>') === false || strpos($html, '</body>') === false)
48
        {
49 17
            return sprintf('<body>%s</body>', $html);
50
        }
51
52
        return $html;
53
    }
54
}
55