Completed
Pull Request — master (#112)
by Richard
02:58
created

Template::run()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
c 7
b 0
f 0
dl 0
loc 16
rs 8.8571
cc 5
eloc 10
nc 5
nop 2
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
	private $functionSet;
13
	private $xPath;
14
15
	public function __construct(\Transphporm\Hook\ElementData $elementData, \Transphporm\Parser\CssToXpath $xPath, \Transphporm\FunctionSet $functionSet, &$baseDir) {
16
		$this->baseDir = &$baseDir;
17
		$this->elementData = $elementData;
18
		$this->functionSet = $functionSet;
19
		$this->xPath = $xPath;
20
	}
21
22
	private function readArray($array, $index) {
23
		return isset($array[$index]) ? $array[$index] : null;
24
	}
25
26
	public function run(array $args, \DomElement $element) {
27
		$selector = $this->readArray($args, 1);
28
		$tss = $this->readArray($args, 2);
29
30
		if (is_file($this->baseDir . $args[0])) $xmlFile = $this->baseDir . $args[0];
31
		elseif (is_file($args[0])) $xmlFile = $args[0];
32
		else throw new \Exception('XML File "' . $args[0] .'" does not exist');
33
34
		$newTemplate = new \Transphporm\Builder($xmlFile, $tss ? $this->baseDir . $tss : null);
35
36
		$doc = $newTemplate->output($this->elementData->getData($element), true)->body;
37
		if ($selector != '') return $this->templateSubsection($doc, $selector);
38
39
		return $this->getTemplateContent($doc, $tss);
40
41
	}
42
43
	private function getTemplateContent($document, $tss) {
44
		$newNode = $document->documentElement;
45
		$result = [];
46
		if ($newNode->tagName === 'template') {
47
			foreach ($newNode->childNodes as $node) {
48
				$result[] = $this->getClonedElement($node, $tss);
49
			}
50
		}
51
		return $result;
52
	}
53
54
	private function templateSubsection($doc, $selector) {
55
		$xpathStr = $this->xPath->getXpath($selector);
56
		$xpath = new \DomXpath($doc);
57
		$nodes = $xpath->query($xpathStr);
58
		$result = [];
59
		foreach ($nodes as $node) {
60
			$result[] = $node;
61
		}
62
		return $result;
63
	}
64
65
	private function getClonedElement($node, $tss) {
66
		$clone = $node->cloneNode(true);
67
		if ($tss != null && $clone instanceof \DomElement) $clone->setAttribute('transphporm', 'includedtemplate');
68
		return $clone;
69
	}
70
}
71