Completed
Pull Request — develop (#120)
by Vladimir
02:04
created

HtmlUtils   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 20
cts 22
cp 0.9091
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 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 11
    public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery)
13
    {
14 11
        $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 11
        libxml_use_internal_errors(true);
17
18 11
        $DOMDocument->loadHTML(
19 11
            mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'),
20 11
            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
21 11
        );
22
23 11
        $xmlErrors = libxml_get_errors();
24
25
        /** @var \LibXMLError $error */
26 11
        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 1
            {
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 11
        }
37
38 11
        libxml_clear_errors();
39
40 11
        $xpath = new \DOMXPath($DOMDocument);
41
42 11
        return $xpath->query($xpathQuery);
43
    }
44
45
    /**
46
     * Add HTML wrapper to content if an XML string does not exist.
47
     *
48
     * @param string $html
49
     *
50
     * @return string
51
     */
52 11
    private static function normalizeHTML($html)
53
    {
54 11
        if (strpos($html, '<body>') === false || strpos($html, '</body>') === false)
55 11
        {
56 11
            return sprintf('<body>%s</body>', $html);
57
        }
58
59
        return $html;
60
    }
61
}
62