1
|
|
|
<?php |
2
|
|
|
/* @description Transformation Style Sheets - Revolutionising PHP templating * |
3
|
|
|
* @author Tom Butler [email protected] * |
4
|
|
|
* @copyright 2015 Tom Butler <[email protected]> | https://r.je/ * |
5
|
|
|
* @license http://www.opensource.org/licenses/bsd-license.php BSD License * |
6
|
|
|
* @version 1.0 */ |
7
|
|
|
namespace Transphporm\TSSFunction; |
8
|
|
|
/* Handles template() function calls from the stylesheet */ |
9
|
|
|
class Template implements \Transphporm\TSSFunction { |
10
|
|
|
private $elementData; |
11
|
|
|
private $baseDir; |
12
|
|
|
|
13
|
|
|
public function __construct(\Transphporm\Hook\ElementData $elementData, &$baseDir) { |
14
|
|
|
$this->baseDir = &$baseDir; |
15
|
|
|
$this->elementData = $elementData; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
private function readArray($array, $index) { |
19
|
|
|
return isset($array[$index]) ? $array[$index] : null; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function run(array $args, \DomElement $element) { |
23
|
|
|
$selector = $this->readArray($args, 1); |
24
|
|
|
$tss = $this->readArray($args, 2); |
25
|
|
|
$newTemplate = new \Transphporm\Builder($this->baseDir . $args[0], $tss ? $this->baseDir . $tss : null); |
26
|
|
|
|
27
|
|
|
$doc = $newTemplate->output($this->elementData->getData($element), true)->body; |
28
|
|
|
if ($selector != '') return $this->templateSubsection($doc, $selector); |
29
|
|
|
|
30
|
|
|
return $this->getTemplateContent($doc, $tss); |
31
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private function getTemplateContent($document, $tss) { |
35
|
|
|
$newNode = $document->documentElement; |
36
|
|
|
$result = []; |
37
|
|
|
if ($newNode->tagName === 'template') { |
38
|
|
|
foreach ($newNode->childNodes as $node) { |
39
|
|
|
$result[] = $this->getClonedElement($node, $tss); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
return $result; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function templateSubsection($doc, $selector) { |
46
|
|
|
$xpathStr = (new \Transphporm\Parser\CssToXpath($selector, new \Transphporm\Parser\Value($this)))->getXpath(); |
47
|
|
|
$xpath = new \DomXpath($doc); |
48
|
|
|
$nodes = $xpath->query($xpathStr); |
49
|
|
|
$result = []; |
50
|
|
|
foreach ($nodes as $node) { |
51
|
|
|
$result[] = $node; |
52
|
|
|
} |
53
|
|
|
return $result; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function getClonedElement($node, $tss) { |
57
|
|
|
$clone = $node->cloneNode(true); |
58
|
|
|
if ($tss != null && $clone instanceof \DomElement) $clone->setAttribute('transphporm', 'includedtemplate'); |
59
|
|
|
return $clone; |
60
|
|
|
} |
61
|
|
|
} |