Completed
Push — master ( c42a51...da7c37 )
by Tom
01:57
created

SheetLoader::updateRequired()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2017 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.2                                                             */
7
namespace Transphporm;
8
//Separates out TSS file loading/caching from parsing
9
class SheetLoader {
10
    private $cache;
11
    private $sheet;
12
    private $time;
13
    private $import = [];
14
    private $cacheKey;
15
    private $rules;
16
    private $cacheName;
17
18
    public function __construct(Cache $cache, FilePath $filePath, $tss, $time) {
19
    	$this->cache = $cache;
20
        $this->filePath = $filePath;
0 ignored issues
show
Bug introduced by
The property filePath does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
21
        $this->tss = $tss;
0 ignored issues
show
Bug introduced by
The property tss does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22
        $this->time = $time ?? time();
23
        $this->cacheName = $tss;
24
    }
25
26
	private function getRulesFromCache($file) {
27
		//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet
28
		$rules = $this->cache->load($this->cacheName, filemtime($file));
29
30
		$this->cacheKey = $this->cacheKey ?? $rules['cacheKey'] ?? null;
31
32
		if ($rules) {
33
			foreach ($rules['import'] as $file) {
34
				//Check that the import file hasn't been changed since the cache was written
35
				if (filemtime($file) > $rules['ctime']) return false;
36
			}
37
		}
38
39
		return $rules;
40
	}
41
	//Allows controlling whether any updates are required to the template
42
	//e.g. return false
43
	//	 1. If all update-frequencies  haven't expired
44
	//   2. If the data hasn't changed since the last run
45
	//If this function returns false, the rendered template is sent straight from the cache skipping 99% of transphporm's code
46
	public function updateRequired($data) {
47
		if (!is_file($this->tss)) return true;
48
49
		$this->cacheName = $this->getCacheKey($data) . $this->tss;
50
51
		$rules = $this->getRulesFromCache($this->tss, $data);
0 ignored issues
show
Unused Code introduced by
The call to SheetLoader::getRulesFromCache() has too many arguments starting with $data.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
52
		//Nothing was cached or the TSS file has changed, update is required
53
		if (empty($rules)) return true;
54
55
		//Find the sheet's minimum update-frequency, if it hasn't passed then no updates are required
56
		if ($rules['ctime']+$rules['minFreq'] <= $this->time) return true;
57
58
		return false;
59
	}
60
61
	//Gets the minimum update-frequency for a sheet's rules
62
	public function getMinUpdateFreq($rules) {
63
		$min = \PHP_INT_MAX;
64
65
		foreach ($rules as $rule) {
66
			$ruleFreq = $rule->getUpdateFrequency();
67
			if ($ruleFreq < $min) $min = $ruleFreq;
68
		}
69
70
		return $min;
71
	}
72
73
	public function addImport($import) {
74
		$this->import[] = $import;
75
	}
76
77
	public function setCacheKey($tokens) {
78
		$this->cacheKey = $tokens;
79
	}
80
81
	public function getCacheKey($data) {
82
		if (is_file($this->tss)) $this->getRulesFromCache($this->tss);
83
		if ($this->cacheKey) {
84
			$parser = new Parser\Value($data);
85
			$x= $parser->parseTokens($this->cacheKey)[0];
86
			$this->cacheName = $x . $this->tss;
87
			return $x;
88
		}
89
		else return '';
90
	}
91
92
	//write the sheet to cache
93
    public function write($file, $rules, $imports = []) {
94
		if (is_file($file)) {
95
			$existing = $this->cache->load($file, filemtime($file));
96
			if (isset($existing['import']) && empty($imports)) $imports = $existing['import'];
97
			$this->cache->write($this->cacheName, ['rules' => $rules, 'import' => $imports, 'minFreq' => $this->getMinUpdateFreq($rules), 'ctime' => $this->time, 'cacheKey' => $this->cacheKey]);
98
		}
99
		return $rules;
100
    }
101
102
	public function processRules($template, \Transphporm\Config $config) {
103
		$rules = $this->getRules($this->tss, $config->getCssToXpath(), $config->getValueParser());
104
105
		usort($rules, [$this, 'sortRules']);
106
		foreach ($rules as $rule) {
107
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $config);
108
		}
109
110
		if (is_file($this->tss)) $this->write($this->tss, $rules, $this->import);
111
	}
112
113
	//Load the TSS
114
	public function getRules($tss, $cssToXpath, $valueParser) {
115
		if (is_file($tss)) {
116
    		//$rules = $this->cache->load($tss);
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
117
    		$rules = $this->getRulesFromCache($tss)['rules'];
118
			$this->filePath->addPath(dirname(realpath($tss)));
119
			if (empty($rules)) $tss = file_get_contents($tss);
120
			else return $rules;
121
    	}
122
		return $tss == null ? [] : (new Parser\Sheet($tss, $cssToXpath, $valueParser, $this->filePath, $this))->parse();
123
	}
124
	//Process a TSS rule e.g. `ul li {content: "foo"; format: bar}
125
	private function executeTssRule($rule, $template, $config) {
126
		$rule->touch();
127
128
		$pseudoMatcher = $config->createPseudoMatcher($rule->pseudo);
129
		$hook = new Hook\PropertyHook($rule->properties, $config->getLine(), $rule->file, $rule->line, $pseudoMatcher, $config->getValueParser(), $config->getFunctionSet(), $config->getFilePath());
0 ignored issues
show
Bug introduced by
$config->getLine() cannot be passed to __construct() as the parameter $configLine expects a reference.
Loading history...
130
		$config->loadProperties($hook);
131
		$template->addHook($rule->query, $hook);
132
	}
133
134
135
	private function sortRules($a, $b) {
136
		//If they have the same depth, compare on index
137
		if ($a->query === $b->query) return $this->sortPseudo($a, $b);
138
139
		if ($a->depth === $b->depth) $property = 'index';
140
		else $property = 'depth';
141
142
		return ($a->$property < $b->$property) ? -1 : 1;
143
	}
144
145
146
	private function sortPseudo($a, $b) {
147
		return count($a->pseudo) < count($b->pseudo)  ? -1  :1;
148
	}
149
}
150