Completed
Push — master ( 2fb808...7b88cf )
by Richard
02:59
created

CssToXpath::splitOnToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 9
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 9
loc 9
rs 9.6666
cc 3
eloc 7
nc 3
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\Parser;
8
class CssToXpath {
9
	private $specialChars = [Tokenizer::WHITESPACE, Tokenizer::DOT, Tokenizer::GREATER_THAN, '~', Tokenizer::NUM_SIGN, Tokenizer::COLON, Tokenizer::OPEN_SQUARE_BRACKET];
10
	private $translators = [];
11
	private $valueParser;
12
	private static $instances = [];
13
	private $functionSet;
14
15
16
	public function __construct(Value $valueParser, \Transphporm\FunctionSet $functionSet, $prefix = '') {
17
		$hash = $this->registerInstance();
18
		$this->valueParser = $valueParser;
19
		$this->functionSet = $functionSet;
20
21
		$this->translators = [
22
			Tokenizer::WHITESPACE => function($string) use ($prefix) { return '//' . $prefix . $string;	},
23
			'' => function($string) use ($prefix) { return '/' . $prefix . $string;	},
24
			Tokenizer::GREATER_THAN => function($string) use ($prefix) { return '/' . $prefix  . $string; },
25
			Tokenizer::NUM_SIGN => function($string) { return '[@id=\'' . $string . '\']'; },
26
			Tokenizer::DOT => function($string) { return '[contains(concat(\' \', normalize-space(@class), \' \'), \' ' . $string . ' \')]'; },
27
			Tokenizer::OPEN_SQUARE_BRACKET => function($string) use ($hash) { return '[' .'php:function(\'\Transphporm\Parser\CssToXpath::processAttr\', \'' . json_encode($string) . '\', ., "' . $hash . '")' . ']';	}
28
		];
29
	}
30
31
	private function registerInstance() {
32
		$hash = spl_object_hash($this);
33
		self::$instances[$hash] = $this;
34
		return $hash;
35
	}
36
37
	private function createSelector() {
38
		$selector = new \stdclass;
39
		$selector->type = '';
40
		$selector->string = '';
41
		return $selector;
42
	}
43
44
	//XPath only allows registering of static functions... this is a hacky workaround for that
45
	public static function processAttr($attr, $element, $hash) {
46
		$attr = json_decode($attr, true);
47
		$valueParser = self::$instances[$hash]->valueParser;
0 ignored issues
show
Unused Code introduced by
$valueParser is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
48
		$functionSet = self::$instances[$hash]->functionSet;
49
		$functionSet->setElement($element[0]);
50
51
		$attributes = array();
52
        foreach($element[0]->attributes as $attribute_name => $attribute_node) {
53
            $attributes[$attribute_name] = $attribute_node->nodeValue;
54
        }
55
56
        $parser = new \Transphporm\Parser\Value($functionSet, true);
57
		$return = $parser->parseTokens($attr, $attributes);
58
59
		return $return[0] === '' ? false : $return[0];
60
	}
61
62 View Code Duplication
	private function splitOnToken($tokens, $splitOn) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
63
		$splitTokens = [];
64
		$i = 0;
65
		foreach ($tokens as $token) {
66
			if ($token['type'] === $splitOn) $i++;
67
			else $splitTokens[$i][] = $token;
68
		}
69
		return $splitTokens;
70
	}
71
72
	//split the css into indivudal functions
73
	private function split($css) {
74
		$selectors = [];
75
		$selector = $this->createSelector();
76
		$selectors[] = $selector;
77
78
		foreach ($css as $token) {
79
			if (in_array($token['type'], $this->specialChars)) {
80
				$selector = $this->createSelector();
81
				$selector->type = $token['type'];
82
				$selectors[] = $selector;
83
			}
84
			if (isset($token['value'])) $selectors[count($selectors)-1]->string = $token['value'];
85
		}
86
		return $selectors;
87
	}
88
89
	public function getXpath($css) {
90
		foreach ($css as $key => $token) {
91
			if ($token['type'] === Tokenizer::WHITESPACE &&
92
				(isset($css[$key+1]) && $css[$key+1]['type'] === Tokenizer::GREATER_THAN)) unset($css[$key]);
93
			else if ($token['type'] === Tokenizer::WHITESPACE &&
94
				(isset($css[$key-1]) && $css[$key-1]['type'] === Tokenizer::GREATER_THAN)) unset($css[$key]);
95
		}
96
		$css = $this->splitOnToken(array_values($css), Tokenizer::COLON)[0];
97
		$selectors = $this->split($css);
98
		$xpath = '/';
99
		foreach ($selectors as $selector) {
100
			if (isset($this->translators[$selector->type])) $xpath .= $this->translators[$selector->type]($selector->string, $xpath);
101
		}
102
103
		$xpath = str_replace('/[', '/*[', $xpath);
104
105
		return $xpath;
106
	}
107
108
	public function getDepth($css) {
109
		return count($this->split($css));
110
	}
111
112
	public function getPseudo($css) {
113
		$parts = $this->splitOnToken($css, Tokenizer::COLON);
114
		array_shift($parts);
115
		return $parts;
116
	}
117
}
118