Completed
Push — master ( ea6b08...f76372 )
by Tom
02:18
created

Builder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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