Completed
Push — master ( 678b45...fc8189 )
by Tom
03:19
created

Builder::output()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 21
Bugs 1 Features 0
Metric Value
c 21
b 1
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 14
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
		$valueParser = new ValueParser($data);
35
		$headers = [];
36
		$this->registerBasicProperties($data, $locale, $headers);
37
38
		$cachedOutput = $this->loadTemplate();
39
		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
40
		$template = new Template($this->isValidDoc($cachedOutput['body']) ? str_ireplace('<!doctype', '<!DOCTYPE', $cachedOutput['body']) : '<template>' . $cachedOutput['body'] . '</template>' );
41
42
		//Allow $time to be set via arguments to spoof time passage during tests
43
		foreach ($this->getRules($template, $valueParser) as $rule) {
44
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $data, $valueParser);			
45
		}
46
		
47
		$result = ['body' => $template->output($document), 'headers' => array_merge($cachedOutput['headers'], $headers)];
48
		$this->cache->write($this->template, $result);		
49
		$result['body'] = $this->doPostProcessing($template)->output($document);
50
51
		return (object) $result;
52
	}
53
54
	//Register the basic properties, content, repeat, display and bind
55
	private function registerBasicProperties($data, $locale, &$headers) {
56
		$formatter = new Hook\Formatter();
57
		$formatter->register(new Formatter\Number($locale));
58
		$formatter->register(new Formatter\Date($locale));
59
		$formatter->register(new Formatter\StringFormatter());
60
		
61
		foreach ($this->formatters as $format) $formatter->register($format);
62
63
		$this->registerProperty('content', new Property\Content($data, $headers, $formatter));
64
		$this->registerProperty('repeat', new Property\Repeat($data));
65
		$this->registerProperty('display', new Property\Display);
66
		$this->registerProperty('bind', new Property\Bind($data));
67
	}
68
69
	//Add a postprocessing hook. This cleans up anything transphporm has added to the markup which needs to be removed
70
	private function doPostProcessing($template) {
71
		$template->addHook('//*[@transphporm]', new Hook\PostProcess());
72
		return $template;
73
	}
74
75
	//Process a TSS rule e.g. `ul li {content: "foo"; format: bar}
76
	private function executeTssRule($rule, $template, $data, $valueParser) {
77
		$rule->touch();
78
		$hook = new Hook\Rule($rule->properties, new Hook\PseudoMatcher($rule->pseudo, $data), $valueParser);
79
		foreach ($this->registeredProperties as $name => $property) $hook->registerProperty($name, $property);
80
		$template->addHook($rule->query, $hook);
81
	}
82
83
	//Load a template, firstly check if it's a file or a valid string
84
	private function loadTemplate() {
85
		if (trim($this->template)[0] !== '<') {			
86
			$xml = $this->cache->load($this->template, filemtime($this->template));
87
			return $xml ? $xml : ['body' => file_get_contents($this->template), 'headers' => []];
88
		}
89
		else return ['body' => $this->template, 'headers' => []];	
90
	}
91
92
	//Load the TSS rules either from a file or as a string
93
	//N.b. only files can be cached
94
	private function getRules($template, $valueParser) {		
95
		if (is_file($this->tss)) {
96
			$this->baseDir = dirname(realpath($this->tss)) . DIRECTORY_SEPARATOR;
97
			//The cache for the key: the filename and template prefix
98
			//Each template may have a different prefix which changes the parsed TSS,
99
			//Because of this the cache needs to be generated for each template prefix.
100
			$key = $this->tss . $template->getPrefix() . $this->baseDir;
101
			//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet
102
			$rules = $this->cache->load($key, filemtime($this->tss));
103
			if (!$rules) return $this->cache->write($key, (new Sheet(file_get_contents($this->tss), $this->baseDir, $valueParser, $template->getPrefix()))->parse());
104
			else return $rules;
105
		}
106
		else return (new Sheet($this->tss, $this->baseDir, $valueParser, $template->getPrefix()))->parse();
107
	}
108
109
	public function setCache(\ArrayAccess $cache) {
110
		$this->cache = new Cache($cache);
111
	}
112
113
	private function getLocale() {
114
		if (is_array($this->locale)) return $this->locale;
115
		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);
116
		else return json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter' . DIRECTORY_SEPARATOR . 'Locale' . DIRECTORY_SEPARATOR . 'enGB.json'), true);
117
	}
118
119
	public function registerProperty($name, Property $property) {
120
		$this->registeredProperties[$name] = $property;
121
	}
122
123
	public function registerFormatter($formatter) {
124
		$this->formatters[] = $formatter;
125
	}
126
127
	public function setLocale($locale) {
128
		$this->locale = $locale;
129
	}
130
131
	private function isValidDoc($xml) {
132
		return strpos($xml, '<!') === 0 || strpos($xml, '<?') === 0;
133
	}
134
}
135