Completed
Push — master ( d03e02...d311a0 )
by Richard
02:56
created

Sheet::import()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 5
rs 9.4285
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         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 $baseDir;
12
	private $valueParser;
13
	private $xPath;
14
15
	public function __construct($tss, $baseDir, CssToXpath $xPath, Value $valueParser) {
16
		$this->tss = $this->stripComments($tss, '//', "\n");
17
		$this->tss = $this->stripComments($this->tss, '/*', '*/');
18
		$tokenizer = new Tokenizer($this->tss);
19
		$this->tss = $tokenizer->getTokens();
20
		$this->baseDir = $baseDir;
21
		$this->xPath = $xPath;
22
		$this->valueParser = $valueParser;
23
	}
24
25
	public function parse($indexStart = 0) {
26
		$rules = [];
27
		$numOfTokens = count($this->tss);
28
		for ($i = 0; isset($this->tss[$i]) && $i <= $numOfTokens; $i++) {
29
			if ($this->tss[$i]['type'] === Tokenizer::WHITESPACE) continue;
30
			if ($processing = $this->processingInstructions($i, count($rules)+$indexStart)) {
31
				$i = $processing['endPos']+1;
32
				$rules = array_merge($rules, $processing['rules']);
33
				continue;
34
			}
35
			$tokens = array_slice($this->tss, $i);
36
			$selector = $this->splitOnToken($tokens, Tokenizer::OPEN_BRACE)[0];
37
			$i += count($selector);
38
			if ($selector[count($selector)-1]['type'] === Tokenizer::WHITESPACE) array_pop($selector);
39
			if (!isset($this->tss[$i])) break;
40
41
			$newRules = $this->cssToRules($selector, count($rules)+$indexStart, $this->getProperties($this->tss[$i]['value']));
42
			$rules = $this->writeRule($rules, $newRules);
43
		}
44
		usort($rules, [$this, 'sortRules']);
45
		if (empty($rules) && !empty($this->tss)) throw new \Exception("No TSS rules parsed");
46
		return $rules;
47
	}
48
49
	private function CssToRules($selector, $index, $properties) {
50
		//$parts = explode(',', $selector);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
51
		$parts = $this->splitOnToken($selector, Tokenizer::ARG);
52
		$rules = [];
53
		foreach ($parts as $part) {
54
			//$tokenizer = new Tokenizer($part);
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
55
			$tokenCss = $part;
56
			$rules[json_encode($part)] = new \Transphporm\Rule($this->xPath->getXpath($tokenCss), $this->xPath->getPseudo($tokenCss), $this->xPath->getDepth($tokenCss), $this->baseDir, $index++);
57
			$rules[json_encode($part)]->properties = $properties;
58
		}
59
		return $rules;
60
	}
61
62
	private function writeRule($rules, $newRules) {
63
		foreach ($newRules as $selector => $newRule) {
64
			if (isset($rules[$selector])) {
65
				$newRule->properties = array_merge($rules[$selector]->properties, $newRule->properties);
66
			}
67
			$rules[$selector] = $newRule;
68
		}
69
70
		return $rules;
71
	}
72
73
	private function processingInstructions($key, $indexStart) {
74
		if (isset($this->tss[$key]) && $this->tss[$key]['type'] !== Tokenizer::AT_SIGN) return false;
75
		$rules = [];
76
		$tokens = array_slice($this->tss, $key+1);
77
		$tokens = $this->splitOnToken($tokens, Tokenizer::SEMI_COLON)[0];
78
		$pos = $key+count($tokens)+1;
79
		$funcName = array_shift($tokens)['value'];
80
		$args = $this->valueParser->parseTokens($tokens);
81
		$rules = array_merge($rules, $this->$funcName($args, $indexStart));
82
		return ['endPos' => $pos, 'rules' => $rules];
83
	}
84
85
	private function import($args, $indexStart) {
86
		$fileName = $args[0];
87
		$sheet = new Sheet(file_get_contents($this->baseDir . $fileName), dirname(realpath($this->baseDir . $fileName)) . DIRECTORY_SEPARATOR, $this->xPath, $this->valueParser);
88
		return $sheet->parse($indexStart);
89
	}
90
91
	private function sortRules($a, $b) {
92
		//If they have the same depth, compare on index
93
		if ($a->depth === $b->depth) return $a->index < $b->index ? -1 : 1;
94
95
		return ($a->depth < $b->depth) ? -1 : 1;
96
	}
97
98
	private function stripComments($str, $open, $close) {
99
		$pos = 0;
100
		while (($pos = strpos($str, $open, $pos)) !== false) {
101
			$end = strpos($str, $close, $pos);
102
			if ($end === false) break;
103
			$str = substr_replace($str, '', $pos, $end-$pos+strlen($close));
104
		}
105
106
		return $str;
107
	}
108
109 View Code Duplication
	private function splitOnToken($tokens, $splitOn) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
		$splitTokens = [];
111
		$i = 0;
112
		foreach ($tokens as $token) {
113
			if ($token['type'] === $splitOn) $i++;
114
			else $splitTokens[$i][] = $token;
115
		}
116
		return $splitTokens;
117
	}
118
119
	private function getProperties($str) {
120
		//$tokenizer = new Tokenizer($str);
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
121
		$tokens = $str;
122
123
		$rules = [];
124
		$i = 0;
125
		foreach ($tokens as $token) {
126
			if ($token['type'] === Tokenizer::SEMI_COLON) $i++;
127
			else if ($token['type'] !== Tokenizer::WHITESPACE) $rules[$i][] = $token;
128
		}
129
130
		$return = [];
131
		foreach ($rules as $rule) {
132
			if ($rule[1]['type'] === Tokenizer::COLON) $return[$rule[0]['value']] = array_slice($rule, 2);
133
		}
134
135
		return $return;
136
	}
137
}
138