Completed
Push — master ( 5ec81c...d5ea32 )
by Richard
03:52
created

Builder::setRootDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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