Completed
Push — master ( 4a26e0...a6da3f )
by Richard
02:34
created

Sheet::getRulesFromCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 4
nc 1
nop 0
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         1.0                                                             */
7
namespace Transphporm\Parser;
8
/** Parses a .tss file into individual rules, each rule has a query e,g, `ul li` and a set of rules e.g. `display: none; bind: iteration(id);` */
9
class Sheet {
10
	private $tss;
11
	private $rules;
12
	private $file;
13
	private $baseDir;
14
	private $valueParser;
15
	private $xPath;
16
	private $tokenizer;
17
18
	public function __construct($tss, $templatePrefix, &$baseDir, CssToXpath $xPath, Value $valueParser, \Transphporm\Cache $cache) {
19
		$this->cache = $cache;
0 ignored issues
show
Bug introduced by
The property cache 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...
20
		$this->prefix = $templatePrefix;
0 ignored issues
show
Bug introduced by
The property prefix 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->baseDir = &$baseDir;
22
		if (is_file($tss)) {
23
			$this->file = $tss;
24
			$this->rules = $this->getRulesFromCache($tss, $templatePrefix);
0 ignored issues
show
Unused Code introduced by
The call to Sheet::getRulesFromCache() has too many arguments starting with $tss.

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...
25
			$baseDir = dirname(realpath($tss)) . DIRECTORY_SEPARATOR;
26
			if (empty($this->rules)) $tss = file_get_contents($tss);
27
			else return;
28
		}
29
		$this->tss = $this->stripComments($tss, '//', "\n");
30
		$this->tss = $this->stripComments($this->tss, '/*', '*/');
31
		$this->tokenizer = new Tokenizer($this->tss);
32
		$this->tss = $this->tokenizer->getTokens();
33
		$this->xPath = $xPath;
34
		$this->valueParser = $valueParser;
35
	}
36
37
	private function getRulesFromCache() {
38
		//The cache for the key: the filename and template prefix
39
		//Each template may have a different prefix which changes the parsed TSS,
40
		//Because of this the cache needs to be generated for each template prefix.
41
		$key = $this->getCacheKey();
42
		//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet
43
		$rules = $this->cache->load($key, filemtime($this->file));
44
		return $rules;
45
	}
46
47
	private function getCacheKey() {
48
		return $this->file . $this->prefix . dirname(realpath($this->file)) . DIRECTORY_SEPARATOR;
49
	}
50
51
	public function parse($indexStart = 0) {
52
		if (!empty($this->rules)) return $this->rules;
53
		$rules = [];
54
		$line = 1;
55
		foreach (new TokenFilterIterator($this->tss, [Tokenizer::WHITESPACE]) as $token) {
56
			if ($processing = $this->processingInstructions($token, count($rules)+$indexStart)) {
57
				$this->tss->skip($processing['skip']+1);
58
				$rules = array_merge($rules, $processing['rules']);
59
				continue;
60
			}
61
			else if ($token['type'] === Tokenizer::NEW_LINE) {
62
				$line++;
63
				continue;
64
			}
65
			$selector = $this->tss->from($token['type'], true)->to(Tokenizer::OPEN_BRACE);
66
			$this->tss->skip(count($selector));
67
			if (count($selector) === 0) break;
68
69
			$newRules = $this->cssToRules($selector, count($rules)+$indexStart, $this->getProperties($this->tss->current()['value']), $line);
70
			$rules = $this->writeRule($rules, $newRules);
71
		}
72
		usort($rules, [$this, 'sortRules']);
73
		$this->checkError($rules);
74
		if (!empty($this->file)) $this->cache->write($this->getCacheKey(), $rules);
75
		return $rules;
76
	}
77
78
	private function checkError($rules) {
79
		if (empty($rules) && count($this->tss) > 0) throw new \Exception('No TSS rules parsed');
80
	}
81
82
	private function CssToRules($selector, $index, $properties, $line) {
83
		$parts = $selector->trim()->splitOnToken(Tokenizer::ARG);
84
		$rules = [];
85
		foreach ($parts as $part) {
86
			$part = $part->trim();
87
			$rules[$this->tokenizer->serialize($part)] = new \Transphporm\Rule($this->xPath->getXpath($part), $this->xPath->getPseudo($part), $this->xPath->getDepth($part), $index++, $this->file, $line);
88
			$rules[$this->tokenizer->serialize($part)]->properties = $properties;
89
		}
90
		return $rules;
91
	}
92
93
	private function writeRule($rules, $newRules) {
94
		foreach ($newRules as $selector => $newRule) {
95
96
			if (isset($rules[$selector])) {
97
				$newRule->properties = array_merge($rules[$selector]->properties, $newRule->properties);
98
			}
99
			$rules[$selector] = $newRule;
100
		}
101
102
		return $rules;
103
	}
104
105
	private function processingInstructions($token, $indexStart) {
106
		if ($token['type'] !== Tokenizer::AT_SIGN) return false;
107
		$tokens = $this->tss->from(Tokenizer::AT_SIGN, false)->to(Tokenizer::SEMI_COLON, false);
108
		$funcName = $tokens->from(Tokenizer::NAME, true)->read();
109
		$args = $this->valueParser->parseTokens($tokens->from(Tokenizer::NAME));
110
		$rules = $this->$funcName($args, $indexStart);
111
112
		return ['skip' => count($tokens)+1, 'rules' => $rules];
113
	}
114
115
	private function import($args, $indexStart) {
116
		if ($this->file !== null) $fileName = dirname(realpath($this->file)) . DIRECTORY_SEPARATOR . $args[0];
117
		else $fileName = $args[0];
118
		$sheet = new Sheet($fileName, $this->prefix, $this->baseDir, $this->xPath, $this->valueParser, $this->cache);
119
		return $sheet->parse($indexStart);
120
	}
121
122
	private function sortRules($a, $b) {
123
		//If they have the same depth, compare on index
124
		if ($a->depth === $b->depth) return $a->index < $b->index ? -1 : 1;
125
126
		return ($a->depth < $b->depth) ? -1 : 1;
127
	}
128
129
	private function stripComments($str, $open, $close) {
130
		$pos = 0;
131
		while (($pos = strpos($str, $open, $pos)) !== false) {
132
			$end = strpos($str, $close, $pos);
133
			if ($end === false) break;
134
			$str = substr_replace($str, '', $pos, $end-$pos+strlen($close));
135
		}
136
137
		return $str;
138
	}
139
140
	private function getProperties($tokens) {
141
        $rules = $tokens->splitOnToken(Tokenizer::SEMI_COLON);
142
143
        $return = [];
144
        foreach ($rules as $rule) {
145
            $name = $rule->from(Tokenizer::NAME, true)->to(Tokenizer::COLON)->read();
146
            $return[$name] = $rule->from(Tokenizer::COLON)->trim();
147
        }
148
149
        return $return;
150
    }
151
}
152