Completed
Pull Request — master (#87)
by Vladimir
02:24
created

HtmlUtils   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 41
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A htmlXPath() 0 28 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 7
    public static function htmlXPath(\DOMDocument &$DOMDocument, $html, $xpathQuery)
13
    {
14 7
        $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 7
        libxml_use_internal_errors(true);
17
18 7
        $DOMDocument->loadHTML($html);
19
20 7
        $xmlErrors = libxml_get_errors();
21
22
        /** @var \LibXMLError $error */
23 7
        foreach ($xmlErrors as $error)
24
        {
25
            // http://www.xmlsoft.org/html/libxml-xmlerror.html#xmlParserErrors
26 1
            if ($error->code === 801)
27 1
            {
28
                continue;
29
            }
30
31 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...
32 7
        }
33
34 7
        libxml_clear_errors();
35
36 7
        $xpath = new \DOMXPath($DOMDocument);
37
38 7
        return $xpath->query($xpathQuery);
39
    }
40
41 7
    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...
42
    {
43 7
        if (strpos($html, '<body>' === false) || strpos($html, '</body>') === false)
44 7
        {
45 7
            return sprintf('<body>%s</body>', $html);
46
        }
47
48
        return $html;
49
    }
50
}
51