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
|
|
|
|