Skip to content

Commit ea5f7c5

Browse files
author
Greg Bowler
authored
Load components into DOM
1 parent ddcf0ea commit ea5f7c5

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/Dom/Document.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717
namespace Gt\Dom;
1818

19+
use Gt\Core\Path;
1920
use \Gt\Request\Request;
2021
use \Gt\Response\Response;
2122
use \Gt\Response\ResponseContent;
@@ -170,6 +171,7 @@ public function __construct($source = null, $config = null) {
170171
}
171172

172173
$this->tidy();
174+
$this->loadComponents();
173175
}
174176

175177
public function createElement($node,
@@ -302,6 +304,43 @@ public function tidy() {
302304
}
303305
}
304306

307+
/**
308+
* Load custom components and replaces with matching HTML. Custom components
309+
* must have a hyphen in their tag name as per the spec. This allows for
310+
* backwards and forwards compatibility as other HTML elements are
311+
* introduced.
312+
*/
313+
public function loadComponents() {
314+
$componentDirectory = Path::get(Path::COMPONENT);
315+
$xpath = new \DOMXPath($this->domDocument);
316+
$customNodeList = $xpath->query("//*[contains(name(), '-')]");
317+
for($i = 0; $i < $customNodeList->length; $i++) {
318+
$node = $customNodeList->item($i);
319+
$componentHtmlFile = implode("/", [
320+
$componentDirectory,
321+
$node->tagName . ".html",
322+
]);
323+
if(!is_file($componentHtmlFile)) {
324+
continue;
325+
}
326+
327+
$html = file_get_contents($componentHtmlFile);
328+
$newDoc = new self($html);
329+
330+
while($node->hasChildNodes()) {
331+
$node->removeChild($node->firstChild);
332+
}
333+
334+
$fragment = $this->domDocument->createDocumentFragment();
335+
foreach($newDoc->body->childNodes as $newNode) {
336+
$imported = $this->domDocument->importNode($newNode->domNode, true);
337+
$fragment->appendChild($imported);
338+
}
339+
340+
$node->parentNode->replaceChild($fragment, $node);
341+
}
342+
}
343+
305344
/**
306345
*
307346
*/

0 commit comments

Comments
 (0)