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

Builder::doPostProcessing()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 3
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         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
		$xml = $cachedOutput['body'];
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($xml) ? $xml : '<template>' . $xml . '</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 = ['headers' => array_merge($cachedOutput['headers'], $headers), 'body' => $template->output($document)];
47
		$this->cache->write($this->template, $result);		
48
		$result['body'] = $this->doPostProcessing($template)->output($document);
49
		
50
		return (object) $result;
51
	}
52
53
	private function doPostProcessing($template) {
54
		$template->addHook('//*[@transphporm]', new Hook\PostProcess());
55
		return $template;
56
	}
57
58
	private function executeTssRule($rule, $template, $data) {
59
		$rule->touch();
60
		$hook = new Hook\Rule($rule->properties, new Hook\PseudoMatcher($rule->pseudo, $data), $data);
61
		foreach ($this->registeredProperties as $properties) $hook->registerProperties($properties);
62
		$template->addHook($rule->query, $hook);
63
	}
64
65
	private function loadTemplate() {
66
		if (trim($this->template)[0] !== '<') {			
67
			$xml = $this->cache->load($this->template, filemtime($this->template));
68
			return $xml ? $xml : ['body' => file_get_contents($this->template), 'headers' => []];
69
		}
70
		else return ['body' => $this->template, 'headers' => []];	
71
	}
72
73
	private function getRules($template) {		
74
		if (is_file($this->tss)) {
75
			$this->baseDir = dirname(realpath($this->tss)) . DIRECTORY_SEPARATOR;
76
			$key = $this->tss . $template->getPrefix() . $this->baseDir;
77
			$rules = $this->cache->load($key, filemtime($this->tss));
78
			if (!$rules) return $this->cache->write($key, (new Sheet(file_get_contents($this->tss), $this->baseDir, $template->getPrefix()))->parse());
79
			else return $rules;
80
		}
81
		else return (new Sheet($this->tss, $this->baseDir, $template->getPrefix()))->parse();
82
	}
83
84
	private function getBasicProperties($data, $locale, &$headers) {
85
		$basicProperties = new Hook\BasicProperties($data, $headers);
86
		$basicProperties->registerFormatter(new Formatter\Number($locale));
87
		$basicProperties->registerFormatter(new Formatter\Date($locale));
88
		$basicProperties->registerFormatter(new Formatter\StringFormatter());
89
		foreach ($this->formatters as $formatter) $basicProperties->registerFormatter($formatter);
90
91
		return isset($this->userCache) ? new Hook\Cache($basicProperties, $this->userCache) : $basicProperties;
92
	}
93
94
	public function setCache(\ArrayAccess $cache) {
95
		$this->cache = new Cache($cache);
96
	}
97
98
	private function getLocale() {
99
		if (is_array($this->locale)) return $this->locale;
100
		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);
101
		else return json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Formatter' . DIRECTORY_SEPARATOR . 'Locale' . DIRECTORY_SEPARATOR . 'enGB.json'), true);
102
	}
103
104
	public function registerProperties($object) {
105
		$this->registeredProperties[] = $object;
106
	}
107
108
	public function registerFormatter($formatter) {
109
		$this->formatters[] = $formatter;
110
	}
111
112
	public function setLocale($locale) {
113
		$this->locale = $locale;
114
	}
115
116
	private function isValidDoc($xml) {
117
		return strpos($xml, '<!') === 0 || strpos($xml, '<?') === 0;
118
	}
119
}
120