Completed
Push — master ( 9c7a65...e91ae6 )
by Tom
02:52
created

PropertyHook::callProperty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 3
nc 2
nop 3
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
/** Hooks into the template system, gets assigned as `ul li` or similar and `run()` is called with any elements that match */
9
class PropertyHook implements \Transphporm\Hook {
10
	private $rules;
11
	private $valueParser;
12
	private $pseudoMatcher;
13
	private $properties = [];
14
15
	public function __construct(array $rules, PseudoMatcher $pseudoMatcher, \Transphporm\Parser\Value $valueParser) {
16
		$this->rules = $rules;
17
		$this->valueParser = $valueParser;
18
		$this->pseudoMatcher = $pseudoMatcher;
19
	}
20
21
	public function run(\DomElement $element) {	
22
		//Don't run if there's a pseudo element like nth-child() and this element doesn't match it
23
		if (!$this->pseudoMatcher->matches($element)) return;
24
25
		foreach ($this->rules as $name => $value) {
26
			$result = $this->callProperty($name, $element, $this->getArgs($value, $element)) ;
27
			if ($result === false) break;
28
		}
29
	}
30
31
	private function getArgs($value, $element) {
32
		$stringExtractor = new \Transphporm\Parser\StringExtractor(trim($value));
33
		$value = str_replace(', ', ',', $stringExtractor);
34
		$value = str_replace(' + ', '+', $value);
35
		$parts = explode(' ', $value);
36
37
		$args = [];
38
		foreach ($parts as $part) {
39
			$args[] = $this->valueParser->parse($stringExtractor->rebuild($part), $element);
40
		}
41
42
		return $args;
43
	}
44
45
	public function registerProperty($name, \Transphporm\Property $property) {
46
		$this->properties[$name] = $property;
47
	}
48
49
	private function callProperty($name, $element, $value) {
50
		if (isset($this->properties[$name])) return $this->properties[$name]->run($value, $element, $this->rules, $this->pseudoMatcher, $this->properties);
51
		return false;
52
	}
53
}
54