Completed
Push — master ( 23e35e...f8660b )
by Tom
01:53
created

SheetLoader   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 32
c 3
b 0
f 0
lcom 1
cbo 4
dl 0
loc 126
rs 9.6

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getRulesFromCache() 0 17 4
A updateRequired() 0 10 3
A getMinUpdateFreq() 0 10 3
A addImport() 0 3 1
A getCacheKey() 0 3 1
A write() 0 10 4
A processRules() 0 11 4
A getRules() 0 10 4
A executeTssRule() 0 8 1
A sortRules() 0 9 4
A sortPseudo() 0 3 2
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;
0 ignored issues
show
Unused Code introduced by
The property $sheet is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
12
    private $time;
13
    private $import = [];
14
15
    public function __construct(Cache $cache, FilePath $filePath, $tss, $time) {
16
        $this->cache = $cache;
17
        $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...
18
        $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...
19
        $this->time = $time;
20
    }
21
22
	private function getRulesFromCache($file) {
23
		$key = $file;
24
25
		//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet
26
		$ftime = filemtime($file);
27
		$rules = $this->cache->load($key, $ftime);
28
29
		if ($rules) {
30
			foreach ($rules['import'] as $file) {
31
				//Check that the import file hasn't been changed since the cache was written
32
				if (filemtime($file) > $rules['ctime']) return false;
33
			}
34
		}
35
36
37
		return $rules;
38
	}
39
	//Allows controlling whether any updates are required to the template
40
	//e.g. return false
41
	//	 1. If all update-frequencies  haven't expired
42
	//   2. If the data hasn't changed since the last run
43
	public function updateRequired($data) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
		if (!is_file($this->tss)) return true;
45
		$rules = $this->getRulesFromCache($this->tss);
46
		//Nothing was cached or the TSS file has changed, update is required
47
		if (empty($rules)) return true;
48
49
		//TOD: use `getMinUpdateFreq' to determne whether the rules need to be executed again
50
51
		return true;
52
	}
53
54
	//Gets the minimum update-frequency for a sheet's rules
55
	public function getMinUpdateFreq($rules) {
56
		$min = \PHP_INT_MAX;
57
58
		foreach ($rules as $rule) {
59
			$ruleFreq = $rule->getUpdateFrequency();
60
			if ($ruleFreq < $min) $min = $ruleFreq;
61
		}
62
63
		return $min;
64
	}
65
66
	public function addImport($import) {
67
		$this->import[] = $import;
68
	}
69
70
	private function getCacheKey($file) {
71
		return dirname(realpath($file));
72
	}
73
	//write the sheet to cache
74
    public function write($file, $rules, $imports = []) {
75
76
		if (is_file($file)) {
77
			$key = $this->getCacheKey($file);
78
			$existing = $this->cache->load($key, filemtime($file));
79
			if (isset($existing['import']) && empty($imports)) $imports = $existing['import'];
80
			$this->cache->write($file, ['rules' => $rules, 'import' => $imports, 'minFreq' => $this->getMinUpdateFreq($rules), 'ctime' => time()]);
81
		}
82
		return $rules;
83
    }
84
85
	public function processRules($template, \Transphporm\Config $config) {
86
		$rules = $this->getRules($this->tss, $config->getCssToXpath(), $config->getValueParser());
87
88
		usort($rules, [$this, 'sortRules']);
89
90
		foreach ($rules as $rule) {
91
			if ($rule->shouldRun($this->time)) $this->executeTssRule($rule, $template, $config);
92
		}
93
94
		if (is_file($this->tss)) $this->write($this->tss, $rules, $this->import);
95
	}
96
97
	//Load the TSS
98
	public function getRules($tss, $cssToXpath, $valueParser) {
99
		if (is_file($tss)) {
100
    		//$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...
101
    		$rules = $this->getRulesFromCache($tss)['rules'];
102
			$this->filePath->addPath(dirname(realpath($tss)));
103
			if (empty($rules)) $tss = file_get_contents($tss);
104
			else return $rules;
105
    	}
106
		return $tss == null ? [] : (new Parser\Sheet($tss, $cssToXpath, $valueParser, $this->filePath, $this))->parse();
107
	}
108
109
	//Process a TSS rule e.g. `ul li {content: "foo"; format: bar}
110
	private function executeTssRule($rule, $template, $config) {
111
		$rule->touch();
112
113
		$pseudoMatcher = $config->createPseudoMatcher($rule->pseudo);
114
		$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...
115
		$config->loadProperties($hook);
116
		$template->addHook($rule->query, $hook);
117
	}
118
119
120
	private function sortRules($a, $b) {
121
		//If they have the same depth, compare on index
122
		if ($a->query === $b->query) return $this->sortPseudo($a, $b);
123
124
		if ($a->depth === $b->depth) $property = 'index';
125
		else $property = 'depth';
126
127
		return ($a->$property < $b->$property) ? -1 : 1;
128
	}
129
130
131
	private function sortPseudo($a, $b) {
132
		return count($a->pseudo) < count($b->pseudo)  ? -1  :1;
133
	}
134
}
135