Completed
Push — master ( a6da3f...e38a6e )
by Richard
03:27
created

Sheet::stripComments()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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