Completed
Push — master ( 39abe4...b867be )
by Richard
02:31
created

PseudoMatcher::matches()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 8.8571
cc 5
eloc 10
nc 7
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 $functions = [];
14
15
	public function __construct($pseudo, \Transphporm\Parser\Value $valueParser) {
16
		$this->pseudo = $pseudo;
17
		$this->valueParser = $valueParser;
18
	}
19
20
	public function registerFunction(\Transphporm\Pseudo $pseudo) {
21
		$this->functions[] = $pseudo;
22
	}
23
24
	public function matches($element) {
25
		$matches = true;
26
		foreach ($this->pseudo as $tokens) {
27
			foreach ($this->functions as $function) {
28
				try {
29
					$parts = $this->getFuncParts($tokens);
30
					$matches = $matches && $function->match($parts['name'], $parts['args'], $element);
31
				}
32
				catch (\Exception $e) {
33
					throw new \Transphporm\RunException(\Transphporm\Exception::PSEUDO, $parts['name'], $e);
34
				}
35
			}
36
		}
37
		return $matches;
38
	}
39
40
	private function getFuncParts($tokens) {
41
		$parts = [];
42
		$parts['name'] = $this->getFuncName($tokens);
43
		if ($parts['name'] === null || in_array($parts['name'], ['data', 'iteration', 'root'])) {
44
			$parts['args'] = $this->valueParser->parseTokens($tokens);
45
		}
46
		else if (count($tokens) > 1) {
47
			$tokens->rewind();
48
			$tokens->next();
49
			$parts['args'] = $this->valueParser->parseTokens($tokens->current()['value']);
50
		}
51
		else $parts['args'] = [['']];
52
		return $parts;
53
	}
54
55
	private function getFuncName($tokens) {
56
		if ($tokens->type() === Tokenizer::NAME) return $tokens->read();
57
		return null;
58
	}
59
60
	public function hasFunction($name) {
61
		foreach ($this->pseudo as $tokens) {
62
			if ($name === $this->getFuncName($tokens)) return true;
63
		}
64
	}
65
66
	public function getFuncArgs($name) {
67
		foreach ($this->pseudo as $tokens) {
68
			$parts = $this->getFuncParts($tokens);
69
			if ($name === $parts['name']) return $parts['args'];
70
		}
71
	}
72
}
73