Template::getTemplateContent()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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