Completed
Push — master ( 01cf95...af4941 )
by Tom
02:35
created

Builder::executeTssRule()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

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 2
eloc 5
nc 2
nop 3
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 $userCache;
18
	private $time;
19
20
	public function __construct($template, $tss = '') {
21
		$this->template = $template;
22
		$this->tss = $tss;
23
		$this->cache = new Cache(new \ArrayObject());
24
	}
25
26
	public function setTime($time) {
27
		$this->time = $time;
28
	}
29
30
	public function output($data = null, $document = false) {
31
		$locale = $this->getLocale();
32
		$data = new Hook\DataFunction(new \SplObjectStorage(), $data, $locale, $this->baseDir);
33
		$headers = [];
34
		$this->registerProperties($this->getBasicProperties($data, $locale, $headers));
35
36
		$cachedOutput = $this->loadTemplate();
37
		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
38
		$template = new Template($this->isValidDoc($cachedOutput['body']) ? $cachedOutput['body'] : '<template>' . $cachedOutput['body'] . '</template>' );
39
40
		//Allow $time to be set via arguments to spoof time passage during tests
41
		foreach ($this->getRules($template) as $rule) {
42
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $data);			
43
		}
44
		
45
		$result = ['headers' => array_merge($cachedOutput['headers'], $headers), 'body' => $template->output($document)];
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 doPostProcessing($template) {
53
		$template->addHook('//*[@transphporm]', new Hook\PostProcess());
54
		return $template;
55
	}
56
57
	private function executeTssRule($rule, $template, $data) {
58
		$rule->touch();
59
		$hook = new Hook\Rule($rule->properties, new Hook\PseudoMatcher($rule->pseudo, $data), $data);
60
		foreach ($this->registeredProperties as $properties) $hook->registerProperties($properties);
61
		$template->addHook($rule->query, $hook);
62
	}
63
64
	private function loadTemplate() {
65
		if (trim($this->template)[0] !== '<') {			
66
			$xml = $this->cache->load($this->template, filemtime($this->template));
67
			return $xml ? $xml : ['body' => file_get_contents($this->template), 'headers' => []];
68
		}
69
		else return ['body' => $this->template, 'headers' => []];	
70
	}
71
72
	private function getRules($template) {		
73
		if (is_file($this->tss)) {
74
			$this->baseDir = dirname(realpath($this->tss)) . DIRECTORY_SEPARATOR;
75
			$key = $this->tss . $template->getPrefix() . $this->baseDir;
76
			$rules = $this->cache->load($key, filemtime($this->tss));
77
			if (!$rules) return $this->cache->write($key, (new Sheet(file_get_contents($this->tss), $this->baseDir, $template->getPrefix()))->parse());
78
			else return $rules;
79
		}
80
		else return (new Sheet($this->tss, $this->baseDir, $template->getPrefix()))->parse();
81
	}
82
83
	private function getBasicProperties($data, $locale, &$headers) {
84
		$basicProperties = new Hook\BasicProperties($data, $headers);
85
		$basicProperties->registerFormatter(new Formatter\Number($locale));
86
		$basicProperties->registerFormatter(new Formatter\Date($locale));
87
		$basicProperties->registerFormatter(new Formatter\StringFormatter());
88
		foreach ($this->formatters as $formatter) $basicProperties->registerFormatter($formatter);
89
90
		return isset($this->userCache) ? new Hook\Cache($basicProperties, $this->userCache) : $basicProperties;
91
	}
92
93
	public function setCache(\ArrayAccess $cache) {
94
		$this->cache = new Cache($cache);
95
	}
96
97
	private function getLocale() {
98
		if (is_array($this->locale)) return $this->locale;
99
		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);
100
		else return json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter' . DIRECTORY_SEPARATOR . 'Locale' . DIRECTORY_SEPARATOR . 'enGB.json'), true);
101
	}
102
103
	public function registerProperties($object) {
104
		$this->registeredProperties[] = $object;
105
	}
106
107
	public function registerFormatter($formatter) {
108
		$this->formatters[] = $formatter;
109
	}
110
111
	public function setLocale($locale) {
112
		$this->locale = $locale;
113
	}
114
115
	private function isValidDoc($xml) {
116
		return strpos($xml, '<!') === 0 || strpos($xml, '<?') === 0;
117
	}
118
}
119