Completed
Push — master ( b86211...ed7d82 )
by Tom
02:45
created

Builder::getRules()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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