HTML5Adapter   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
cbo 2
dl 0
loc 60
ccs 27
cts 27
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 15 3
A dump() 0 7 2
A collectMetadata() 0 9 1
A getHtml5() 0 9 2
1
<?php
2
namespace Goetas\Twital\SourceAdapter;
3
4
use Goetas\Twital\SourceAdapter;
5
use Goetas\Twital\Template;
6
use Masterminds\HTML5;
7
8
/**
9
 *
10
 * @author Asmir Mustafic <[email protected]>
11
 *
12
 */
13
class HTML5Adapter implements SourceAdapter
14
{
15
    private $html5;
16
17
    /**
18
     * {@inheritdoc}
19
     */
20 178
    public function load($source)
21
    {
22 178
        $html5 = $this->getHtml5();
23
24 178
        if (stripos(rtrim($source), '<!DOCTYPE html>') === 0) {
25 2
            $dom = $html5->loadHTML($source);
26 2
        } else {
27 176
            $f = $html5->loadHTMLFragment($source);
28 176
            $dom = new \DOMDocument('1.0', 'UTF-8');
29 176
            if ('' !== trim($source)) {
30 175
                $dom->appendChild($dom->importNode($f, true));
31 175
            }
32
        }
33 178
        return new Template($dom, $this->collectMetadata($dom, $source));
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 178
    public function dump(Template $template)
40
    {
41 178
        $metadata = $template->getMetadata();
42 178
        $dom = $template->getDocument();
43 178
        $html5 = $this->getHtml5();
44 178
        return $html5->saveHTML($metadata['fragment'] ? $dom->childNodes : $dom);
45
    }
46
47
    /**
48
     * Collect some metadata about $dom and $content
49
     * @param \DOMDocument $dom
50
     * @param string $source
51
     * @return mixed
52
     */
53 178
    protected function collectMetadata(\DOMDocument $dom, $source)
54
    {
55 178
        $metadata = array();
56
57 178
        $metadata['doctype'] = !!$dom->doctype;
58 178
        $metadata['fragment'] = stripos(rtrim($source), '<!DOCTYPE html>') !== 0;
59
60 178
        return $metadata;
61
    }
62
63 178
    private function getHtml5()
64
    {
65 178
        if (!$this->html5) {
66 178
            $this->html5 = new HTML5(array(
67
                "xmlNamespaces" => true
68 178
            ));
69 178
        }
70 178
        return $this->html5;
71
    }
72
}
73