Completed
Push — master ( 3b6d57...ed50b2 )
by Tom
02:19
created

Builder::output()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 9.3142
cc 3
eloc 14
nc 2
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;
8
/** Builds a Transphorm instance from the 3 constituent parts. XML template string, TSS string and data */
9
class Builder {
10
	private $template;
11
	private $tss;
12
	private $rootDir;
13
	private $cache;
14
	private $time;
15
	private $modules = [];
16
	private $defaultModules = [
17
		'\\Transphporm\\Module\\Basics',
18
		'\\Transphporm\\Module\\Pseudo',
19
		'\\Transphporm\\Module\\Format',
20
		'\\Transphporm\\Module\\Functions'
21
	];
22
23
	public function __construct($template, $tss = '', $modules = null) {
24
		$this->template = $template;
25
		$this->tss = $tss;
26
		$this->cache = new Cache(new \ArrayObject());
27
28
		$modules = is_array($modules) ? $modules : $this->defaultModules;
29
		foreach ($modules as $module) $this->loadModule(new $module);
30
	}
31
32
	//Allow setting the time used by Transphporm for caching. This is for testing purposes
33
	//Would be better if PHP allowed setting the script clock, but this is the simplest way of overriding it
34
	public function setTime($time) {
35
		$this->time = $time;
36
	}
37
38
	public function loadModule(Module $module) {
39
		$this->modules[get_class($module)] = $module;
40
	}
41
42
	public function setRootDir($rootDir) {
43
		$this->rootDir = $rootDir;
44
	}
45
46
	public function output($data = null, $document = false) {
47
		$headers = [];
48
49
		$elementData = new \Transphporm\Hook\ElementData(new \SplObjectStorage(), $data);
50
		$functionSet = new FunctionSet($elementData);
51
52
		$cachedOutput = $this->loadTemplate();
53
		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
54
		$template = new Template($this->isValidDoc($cachedOutput['body']) ? str_ireplace('<!doctype', '<!DOCTYPE', $cachedOutput['body']) : '<template>' . $cachedOutput['body'] . '</template>' );
55
		$valueParser = new Parser\Value($functionSet);
56
		$config = new Config($functionSet, $valueParser, $elementData, new Hook\Formatter(), new Parser\CssToXpath($functionSet, $template->getPrefix()), new FilePath($this->rootDir), $headers);
57
58
		foreach ($this->modules as $module) $module->load($config);
59
60
		$this->processRules($template, $config);
61
62
		$result = ['body' => $template->output($document), 'headers' => array_merge($cachedOutput['headers'], $headers)];
63
		$this->cache->write($this->template, $result);
64
		$result['body'] = $this->doPostProcessing($template)->output($document);
65
		return (object) $result;
66
	}
67
68
	private function processRules($template, $config) {
69
		$rules = $this->getRules($template, $config);
70
71
		foreach ($rules as $rule) {
72
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $config);
73
		}
74
	}
75
76
	//Add a postprocessing hook. This cleans up anything transphporm has added to the markup which needs to be removed
77
	private function doPostProcessing($template) {
78
		$template->addHook('//*[@transphporm]', new Hook\PostProcess());
79
		return $template;
80
	}
81
82
	//Process a TSS rule e.g. `ul li {content: "foo"; format: bar}
83
	private function executeTssRule($rule, $template, $config) {
84
		$rule->touch();
85
86
		$pseudoMatcher = $config->createPseudoMatcher($rule->pseudo);
87
		$hook = new Hook\PropertyHook($rule->properties, $config->getLine(), $rule->file, $rule->line, $pseudoMatcher, $config->getValueParser(), $config->getFunctionSet(), $config->getFilePath());
0 ignored issues
show
Bug introduced by
$config->getLine() cannot be passed to __construct() as the parameter $configLine expects a reference.
Loading history...
88
		$config->loadProperties($hook);
89
		$template->addHook($rule->query, $hook);
90
	}
91
92
	//Load a template, firstly check if it's a file or a valid string
93
	private function loadTemplate() {
94
		if (trim($this->template)[0] !== '<') {
95
			$xml = $this->cache->load($this->template, filemtime($this->template));
96
			return $xml ? $xml : ['body' => file_get_contents($this->template), 'headers' => []];
97
		}
98
		else return ['body' => $this->template, 'headers' => []];
99
	}
100
101
	//Load the TSS rules either from a file or as a string
102
	//N.b. only files can be cached
103
	private function getRules($template, $config) {
104
		$cache = new TSSCache($this->cache, $template->getPrefix());
105
		return (new Parser\Sheet($this->tss, $config->getCssToXpath(), $config->getValueParser(), $cache, $config->getFilePath()))->parse();
106
	}
107
108
	public function setCache(\ArrayAccess $cache) {
109
		$this->cache = new Cache($cache);
110
	}
111
112
	private function isValidDoc($xml) {
113
		return (strpos($xml, '<!') === 0 && strpos($xml, '<!--') !== 0) || strpos($xml, '<?') === 0;
114
	}
115
116
	public function __destruct() {
117
		//Required hack as DomXPath can only register static functions clear any statically stored instances
118
		Parser\CssToXpath::cleanup();
119
	}
120
}
121