Completed
Pull Request — master (#88)
by Vladimir
02:11
created

HtmlUtils::htmlXPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 11
cts 12
cp 0.9167
rs 9.472
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3.0052
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
            {
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
        }
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
        {
45 7
            return sprintf('<body>%s</body>', $html);
46
        }
47
48
        return $html;
49
    }
50
}
51