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

PseudoMatcher::getFuncName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 3
nc 2
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
29
		foreach ($this->pseudo as $tokens) {
30
			foreach ($this->functions as $function) {
31
				$parts = $this->getFuncParts($tokens);
32
				$matches = $matches && $function->match($parts['name'], $parts['args'], $element);
33
			}
34
		}
35
		return $matches;
36
	}
37
38
	private function getFuncParts($tokens) {
39
		$parts = [];
40
		$parts['name'] = $this->getFuncName($tokens);
41
		if ($parts['name'] === null || in_array($parts['name'], ['data', 'iteration', 'root'])) {
42
			$parts['args'] = $this->valueParser->parseTokens($tokens, $this->functionSet);
43
		}
44
		elseif (isset($tokens[1])) $parts['args'] = $this->valueParser->parseTokens($tokens[1]['value'], $this->functionSet);
45
		else $parts['args'] = [['']];
46
		return $parts;
47
	}
48
49
	private function getFuncName($tokens) {
50
		if ($tokens[0]['type'] === Tokenizer::NAME) return $tokens[0]['value'];
51
		return null;
52
	}
53
54
	public function hasFunction($name) {
55
		foreach ($this->pseudo as $tokens) {
56
			if ($name === $this->getFuncName($tokens)) return true;
57
		}
58
	}
59
60
	public function getFuncArgs($name) {
61
		foreach ($this->pseudo as $tokens) {
62
			$parts = $this->getFuncParts($tokens);
63
			if ($name === $parts['name']) return $parts['args'];
64
		}
65
	}
66
}
67