Completed
Pull Request — master (#116)
by Richard
02:25
created

PseudoMatcher::getFuncParts()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
rs 9.2
cc 4
eloc 8
nc 3
nop 1
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\Hook;
8
use \Transphporm\Parser\Tokenizer;
9
/** Determines whether $element matches the pseudo rule such as nth-child() or [attribute="value"] */
10
class PseudoMatcher {
11
	private $pseudo;
12
	private $valueParser;
13
	private $functionSet;
14
	private $functions = [];
15
16
	public function __construct($pseudo, \Transphporm\Parser\Value $valueParser, \Transphporm\FunctionSet $functionSet) {
17
		$this->pseudo = $pseudo;
18
		$this->valueParser = $valueParser;
19
		$this->functionSet = $functionSet;
20
	}
21
22
	public function registerFunction(\Transphporm\Pseudo $pseudo) {
23
		$this->functions[] = $pseudo;
24
	}
25
26
	public function matches($element) {
27
		$matches = true;
28
		$this->functionSet->setElement($element);
29
30
		foreach ($this->pseudo as $tokens) {
31
			foreach ($this->functions as $function) {
32
				$parts = $this->getFuncParts($tokens);
33
				$matches = $matches && $function->match($parts['name'], $parts['args'], $element);
34
			}
35
		}
36
		return $matches;
37
	}
38
39
	private function getFuncParts($tokens) {
40
		$parts = [];
41
		$parts['name'] = $this->getFuncName($tokens);
42
		if ($parts['name'] === null || in_array($parts['name'], ['data', 'iteration', 'root'])) {
43
			$parts['args'] = $this->valueParser->parseTokens($tokens, $this->functionSet);
44
		}
45
		elseif (isset($tokens[1])) $parts['args'] = $this->valueParser->parseTokens($tokens[1]['value'], $this->functionSet);
46
		else $parts['args'] = [['']];
47
		return $parts;
48
	}
49
50
	private function getFuncName($tokens) {
51
		if ($tokens[0]['type'] === Tokenizer::NAME) return $tokens[0]['value'];
52
		return null;
53
	}
54
55
	public function hasFunction($name) {
56
		foreach ($this->pseudo as $tokens) {
57
			if ($name === $this->getFuncName($tokens)) return true;
58
		}
59
	}
60
61
	// TODO: Improve the functionality of getFuncArgs and make it similar to when using `match`
62
	public function getFuncArgs($name, $element) {
63
		$this->functionSet->setElement($element);
64
65
		foreach ($this->pseudo as $tokens) {
66
			$parts = $this->getFuncParts($tokens);
67
			if ($name === $parts['name']) return $parts['args'];
68
		}
69
	}
70
}
71