HTML5Value::setContent()   A
last analyzed

Complexity

Conditions 3
Paths 10

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 26
c 0
b 0
f 0
nc 10
nop 1
dl 0
loc 42
rs 9.504
1
<?php
2
3
namespace SilverStripe\HTML5;
4
5
use Exception;
6
use SilverStripe\View\Parsers\HTMLValue;
7
8
class HTML5Value extends HTMLValue
9
{
10
    public function setContent($content)
11
    {
12
        // Convert any errors to exceptions
13
        set_error_handler(
14
            function ($no, $str) {
15
                throw new Exception("HTML Parse Error: ".$str);
16
            },
17
            error_reporting()
18
        );
19
20
        // Use HTML5 parser to parse the HTML fragment
21
        try {
22
            $content = str_replace("\r\n", "\n", $content);
23
            $parserPath = implode(
24
                DIRECTORY_SEPARATOR,
25
                [
26
                    dirname(__DIR__),
27
                    'thirdparty',
28
                    'html5lib-php',
29
                    'library',
30
                    'HTML5',
31
                    'Parser.php'
32
                ]
33
            );
34
            require_once $parserPath;
35
            $document = \HTML5_Parser::parse(
36
                "<!DOCTYPE html>\n" .
37
                '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>' .
38
                "<body>$content</body></html>"
39
            );
40
        } catch (Exception $e) {
41
            $document = false;
42
        }
43
44
        // Disable our error handler (restoring to previous value)
45
        restore_error_handler();
46
47
        // If we couldn't parse the HTML, set the error state
48
        if ($document) {
49
            $this->setDocument($document);
50
        } else {
51
            $this->setInvalid();
52
        }
53
    }
54
}
55