Completed
Push — master ( aa557b...9caa90 )
by Tom
02:59
created

Builder::processRules()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4286
cc 3
eloc 4
nc 3
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 $registeredProperties = [];
13
	private $formatters = [];
14
	private $locale;
15
	private $baseDir;
16
	private $cache;
17
	private $time;
18
19
	public function __construct($template, $tss = '') {
20
		$this->template = $template;
21
		$this->tss = $tss;
22
		$this->cache = new Cache(new \ArrayObject());
23
	}
24
25
	//Allow setting the time used by Transphporm for caching. This is for testing purposes
26
	//Would be better if PHP allowed setting the script clock, but this is the simplest way of overriding it
27
	public function setTime($time) {
28
		$this->time = $time;
29
	}
30
31
	public function output($data = null, $document = false) {
32
		$locale = $this->getLocale();
33
		$data = new Hook\DataFunction(new \SplObjectStorage(), $data, $locale, $this->baseDir);
34
		$headers = [];
35
		
36
		$propertyBuilder = new PropertyBuilder($this);
37
		$propertyBuilder->registerBasicProperties($data, $locale, $headers, $this->formatters);
38
39
		$cachedOutput = $this->loadTemplate();
40
		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
41
		$template = new Template($this->isValidDoc($cachedOutput['body']) ? str_ireplace('<!doctype', '<!DOCTYPE', $cachedOutput['body']) : '<template>' . $cachedOutput['body'] . '</template>' );
42
43
		$this->processRules($template, $data);
44
		
45
		$result = ['body' => $template->output($document), 'headers' => array_merge($cachedOutput['headers'], $headers)];
46
		$this->cache->write($this->template, $result);		
47
		$result['body'] = $this->doPostProcessing($template)->output($document);
48
49
		return (object) $result;
50
	}
51
52
	private function processRules($template, $data) {
53
		$valueParser = new ValueParser($data);
54
		foreach ($this->getRules($template, $valueParser) as $rule) {
55
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $data, $valueParser);			
56
		}
57
	}
58
59
	//Add a postprocessing hook. This cleans up anything transphporm has added to the markup which needs to be removed
60
	private function doPostProcessing($template) {
61
		$template->addHook('//*[@transphporm]', new Hook\PostProcess());
62
		return $template;
63
	}
64
65
	//Process a TSS rule e.g. `ul li {content: "foo"; format: bar}
66
	private function executeTssRule($rule, $template, $data, $valueParser) {
67
		$rule->touch();
68
		$hook = new Hook\Rule($rule->properties, new Hook\PseudoMatcher($rule->pseudo, $data), $valueParser);
69
		foreach ($this->registeredProperties as $name => $property) $hook->registerProperty($name, $property);
70
		$template->addHook($rule->query, $hook);
71
	}
72
73
	//Load a template, firstly check if it's a file or a valid string
74
	private function loadTemplate() {
75
		if (trim($this->template)[0] !== '<') {			
76
			$xml = $this->cache->load($this->template, filemtime($this->template));
77
			return $xml ? $xml : ['body' => file_get_contents($this->template), 'headers' => []];
78
		}
79
		else return ['body' => $this->template, 'headers' => []];	
80
	}
81
82
	//Load the TSS rules either from a file or as a string
83
	//N.b. only files can be cached
84
	private function getRules($template, $valueParser) {		
85
		if (is_file($this->tss)) {
86
			$this->baseDir = dirname(realpath($this->tss)) . DIRECTORY_SEPARATOR;
87
			//The cache for the key: the filename and template prefix
88
			//Each template may have a different prefix which changes the parsed TSS,
89
			//Because of this the cache needs to be generated for each template prefix.
90
			$key = $this->tss . $template->getPrefix() . $this->baseDir;
91
			//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet
92
			$rules = $this->cache->load($key, filemtime($this->tss));
93
			if (!$rules) return $this->cache->write($key, (new Sheet(file_get_contents($this->tss), $this->baseDir, $valueParser, $template->getPrefix()))->parse());
94
			else return $rules;
95
		}
96
		else return (new Sheet($this->tss, $this->baseDir, $valueParser, $template->getPrefix()))->parse();
97
	}
98
99
	public function setCache(\ArrayAccess $cache) {
100
		$this->cache = new Cache($cache);
101
	}
102
103
	private function getLocale() {
104
		if (is_array($this->locale)) return $this->locale;
105
		else if (strlen($this->locale) > 0) return json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter' . DIRECTORY_SEPARATOR . 'Locale' . DIRECTORY_SEPARATOR . $this->locale . '.json'), true);
106
		else return json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter' . DIRECTORY_SEPARATOR . 'Locale' . DIRECTORY_SEPARATOR . 'enGB.json'), true);
107
	}
108
109
	public function registerProperty($name, Property $property) {
110
		$this->registeredProperties[$name] = $property;
111
	}
112
113
	public function registerFormatter($formatter) {
114
		$this->formatters[] = $formatter;
115
	}
116
117
	public function setLocale($locale) {
118
		$this->locale = $locale;
119
	}
120
121
	private function isValidDoc($xml) {
122
		return strpos($xml, '<!') === 0 || strpos($xml, '<?') === 0;
123
	}
124
}
125