Completed
Push — master ( 0e6890...81e62d )
by Tom
02:57
created

Builder::output()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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