Completed
Push — master ( f8e36b...235894 )
by Tom
02:30
created

CssToXpath::__destruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
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\Parser;
8
class CssToXpath {
9
	private $specialChars = [' ', '.', '>', '~', '#', ':', '[', ']'];
10
	private $translators = [];
11
	private $css;
12
	private $depth;
13
	private static $instances = [];
14
15
	public function __construct($css, Value $valueParser, $prefix = '') {
16
		$hash = $this->registerInstance();
17
		$this->valueParser = $valueParser;
0 ignored issues
show
Bug introduced by
The property valueParser does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
18
		$this->css = str_replace([' >', '> '],['>', '>'], trim($css));
19
		$this->translators = [
20
			' ' => function($string) use ($prefix) { return '//' . $prefix . $string;	},
21
			'' => function($string) use ($prefix) { return '/' . $prefix . $string;	},
22
			'>' => function($string) use ($prefix) { return '/' . $prefix  . $string; },
23
			'#' => function($string) { return '[@id=\'' . $string . '\']'; },
24
			'.' => function($string) { return '[contains(concat(\' \', normalize-space(@class), \' \'), \' ' . $string . ' \')]'; }, 
25
			'[' => function($string, $xpath) use($hash) { return '[' .'php:function(\'\Transphporm\Parser\CssToXpath::processAttr\', \'' . $string . '\', ., "' . $hash . '")' . ']';	},
0 ignored issues
show
Unused Code introduced by
The parameter $xpath is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
26
			']' => function() {	return ''; }
27
		];
28
	}
29
30
	private function registerInstance() {
31
		$hash = spl_object_hash($this);
32
		self::$instances[$hash] = $this;
33
		return $hash;
34
	}
35
36
	private function createSelector() {
37
		$selector = new \stdclass;
38
		$selector->type = '';
39
		$selector->string = '';
40
		return $selector;
41
	}
42
43
	//XPath only allows registering of static functions... this is a hacky workaround for that
44
	public static function processAttr($attr, $element, $hash) {
45
		$comparators = ['!=', '='];
46
		$valueParser = self::$instances[$hash]->valueParser;
47
		foreach ($comparators as $comparator) {
48
			if (strpos($attr, $comparator) !== false) {
49
				$parts = explode($comparator, $attr);
50
				$parts = array_map(function($val) use ($valueParser, $element) {
51
					return $valueParser->parse($val, $element[0])[0];
52
				}, $parts);
53
				
54
				return self::compare($comparator, $element[0]->getAttribute($parts[0]), $parts[1]);
55
			}
56
		}
57
		return $attr;
58
	}
59
60
	private static function compare($comparator, $a, $b) {
61
		if ($comparator == '=') return $a == $b;
62
		else if ($comparator == '!=') return $a != $b;
63
	}
64
65
	//split the css into indivudal functions
66
	private function split($css) {
67
		$selectors = [];
68
		$selector = $this->createSelector();
69
		$selectors[] = $selector;
70
71
		for ($i = 0; $i < strlen($css); $i++) {
72
			if (in_array($css[$i], $this->specialChars)) {
73
				$selector = $this->createSelector();
74
				$selector->type = $css[$i];
75
				$selectors[] = $selector;
76
			}
77
			else $selector->string .= $css[$i];			
78
		}
79
		return $selectors;
80
	}
81
82
	public function getXpath() {
83
		$css = explode(':', $this->css)[0];
84
		$selectors = $this->split($css);
85
		$this->depth = count($selectors);
86
		$xpath = '/';
87
		foreach ($selectors as $selector) {
88
			if (isset($this->translators[$selector->type])) $xpath .= $this->translators[$selector->type]($selector->string, $xpath);
89
		}
90
91
		$xpath = str_replace('/[', '/*[', $xpath);
92
93
		return $xpath;
94
	}
95
96
	public function getDepth() {
97
		return $this->depth;
98
	}
99
	
100
	public function getPseudo() {
101
		$parts = explode(':', $this->css);
102
		array_shift($parts);
103
		return $parts;
104
	}
105
}