Completed
Pull Request — master (#84)
by
unknown
02:36
created

Attribute::match()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 22
rs 8.9197
cc 4
eloc 16
nc 4
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\Pseudo;
8
class Attribute implements \Transphporm\Pseudo {
9
	private $functionSet;
10
11
	public function __construct(\Transphporm\FunctionSet $functionSet) {
12
		$this->functionSet = $functionSet;
13
	}
14
15
	public function match($pseudo, \DomElement $element) {
16
		$pos = strpos($pseudo, '[');
17
		if ($pos === false) return true;
18
19
		$name = substr($pseudo, 0, $pos);
20
		if (!is_callable([$this->functionSet, $name])) return true;
21
22
		$bracketMatcher = new \Transphporm\Parser\BracketMatcher($pseudo);
23
		$criteria = $bracketMatcher->match('[', ']');
24
25
		if (strpos($pseudo, '=') === false) {
26
			$lookupValue = $this->functionSet->$name([$criteria], $element);
27
			return $lookupValue !== null;
28
		}
29
		list ($field, $value) = explode('=', $criteria);
30
31
		$operator = $this->getOperator($field);
32
		$lookupValue = $this->functionSet->$name([trim($field, $operator)], $element);
33
		$valueParser = new \Transphporm\Parser\Value($this->functionSet);
34
		$value = $valueParser->parse($value, $element);
35
		return $this->processOperator($operator, $lookupValue, $this->parseValue(trim($value, '"')));
36
	}
37
38
39
	//Currently only not is supported, but this is separated out to support others in future
40
	private function processOperator($operator, $lookupValue, $value) {
41
		$matched = $lookupValue == $value;
42
		return $operator === '!' ? !$matched : $matched;
43
	}
44
45
	private function parseValue($value) {
46
		if ($value == 'true') return true;
47
		else if ($value == 'false') return false;
48
		else return $value;
49
	}
50
51
	private function getOperator($field) {
52
		if ($field[strlen($field)-1] == '!') {
53
			return '!';
54
		}
55
		else return '';
56
	}
57
58
}
59