Locator   A
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 336
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 99.1%

Importance

Changes 0
Metric Value
wmc 39
lcom 2
cbo 4
dl 0
loc 336
ccs 110
cts 111
cp 0.991
rs 9.28
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A filter_by_at() 0 4 1
A filter_by_value() 0 4 1
A filter_by_text() 0 6 3
A filter_by_visible() 0 4 1
A type() 0 4 1
A selector() 0 4 1
A filters() 0 4 1
A field_to_xpath() 0 12 1
A label_to_xpath() 0 11 1
A link_to_xpath() 0 9 1
A button_to_xpath() 0 13 1
A convert_css_selector_to_xpath() 0 9 2
B is_filtered() 0 41 9
A filter_by_attributes() 0 10 3
B xpath() 0 37 8
A __toString() 0 13 2
1
<?php
2
3
namespace Openbuildings\Spiderling;
4
5
use Symfony\Component\CssSelector;
6
7
/**
8
 * Locator - converts varios locator formats into xpath
9
 *
10
 * @package    Openbuildings\Spiderling
11
 * @author     Ivan Kerin
12
 * @copyright  (c) 2013 OpenBuildings Ltd.
13
 * @license    http://spdx.org/licenses/BSD-3-Clause
14
 */
15
class Locator {
16
17
	const DEFAULT_TYPE = 'css';
18
19
	/**
20
	 * Converted xpath cache
21
	 * @var string
22
	 */
23
	protected $_xpath;
24
25
	/**
26
	 * The type of the locator, can be css, field, xpath, label, link or button
27
	 * @var string
28
	 */
29
	protected $_type;
30
31
	/**
32
	 * The selector used to generate the xpath
33
	 * @var string
34
	 */
35
	protected $_selector;
36
37
	/**
38
	 * Additional filters to apply after the xpath is found
39
	 * @var array
40
	 */
41
	protected $_filters;
42
43
	/**
44
	 * @param string $type
45
	 * @param string $selector
46
	 * @param array $filters
47
	 */
48 67
	function __construct($type, $selector, array $filters = array())
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
49
	{
50 67
		$this->_type = $type === NULL ? self::DEFAULT_TYPE : $type;
51 67
		$this->_selector = $selector;
52 67
		$this->_filters = $filters;
53 67
	}
54
55
	/**
56
	 * Check if a Node item matches the current filters
57
	 * @param  Node    $item
58
	 * @param  integer  $index
59
	 * @return boolean
60
	 */
61 3
	public function is_filtered(Node $item, $index)
62
	{
63 3
		foreach ($this->filters() as $filter => $value)
64
		{
65
			try {
66
				switch ($filter)
67
				{
68 3
					case 'at':
69 2
						$matches_filter = $this->filter_by_at($item, $index, $value);
70 2
					break;
71
72 2
					case 'value':
73 2
						$matches_filter = $this->filter_by_value($item, $index, $value);
74 2
					break;
75
76 2
					case 'text':
77 1
						$matches_filter = $this->filter_by_text($item, $index, $value);
78 1
					break;
79
80 1
					case 'visible':
81 1
						$matches_filter = $this->filter_by_visible($item, $index, $value);
82 1
					break;
83
84 1
					case 'attributes':
85 1
						$matches_filter = $this->filter_by_attributes($item, $index, $value);
86 1
					break;
87
88
					default:
89 1
						throw new Exception('Filter :filter does not exist', array(':filter' => $filter));
90
				}
91
92 3
				if ( ! $matches_filter)
93 3
					return FALSE;
94
95 1
			} catch (Exception_Staleelement $e) {
96 3
				return FALSE;
97
			}
98
		}
99
100 3
		return TRUE;
101
	}
102
103
	/**
104
	 * Try matching "at" filter
105
	 *
106
	 * @param  Node   $item
107
	 * @param  integer $index
108
	 * @param  string $value
109
	 * @return boolean
110
	 */
111 2
	public function filter_by_at(Node $item, $index, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $item 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...
112
	{
113 2
		return $index == $value;
114
	}
115
116
	/**
117
	 * Try matching "value" filter
118
	 *
119
	 * @param  Node   $item
120
	 * @param  integer $index
121
	 * @param  string $value
122
	 * @return boolean
123
	 */
124 2
	public function filter_by_value(Node $item, $index, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $index 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...
125
	{
126 2
		return $item->value() == $value;
127
	}
128
129
	/**
130
	 * Try matching "text" filter
131
	 *
132
	 * @param  Node   $item
133
	 * @param  integer $index
134
	 * @param  string $value
135
	 * @return boolean
136
	 */
137 2
	public function filter_by_text(Node $item, $index, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $index 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...
138
	{
139 2
		$text = $item->text();
140
141 2
		return ($text AND $value AND mb_stripos($text, $value) !== FALSE);
142
	}
143
144
	/**
145
	 * Try matching "visible" filter
146
	 *
147
	 * @param  Node   $item
148
	 * @param  integer $index
149
	 * @param  boolean $value
150
	 * @return boolean
151
	 */
152 1
	public function filter_by_visible(Node $item, $index, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $index 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...
153
	{
154 1
		return $item->is_visible() === $value;
155
	}
156
157
	/**
158
	 * Try matching "attributes" filter
159
	 *
160
	 * @param  Node   $item
161
	 * @param  integer $index
162
	 * @param  array $value
163
	 * @return boolean
164
	 */
165 1
	public function filter_by_attributes(Node $item, $index, array $value)
0 ignored issues
show
Unused Code introduced by
The parameter $index 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...
166
	{
167 1
		foreach ($value as $attribute_name => $attribute_val)
168
		{
169 1
			if ($item->attribute($attribute_name) != $attribute_val)
170 1
				return FALSE;
171
		}
172
173 1
		return TRUE;
174
	}
175
176
	/**
177
	 * Return the xpath representaiton of the selector, using the appropriate method
178
	 * @return string
179
	 */
180 49
	public function xpath()
181
	{
182 49
		if ( ! $this->_xpath)
183
		{
184 49
			switch ($this->type())
185
			{
186 49
				case 'css':
187 20
					$this->_xpath = '//'.$this->convert_css_selector_to_xpath($this->selector());
188 20
				break;
189
190 35
				case 'xpath':
191 1
					$this->_xpath = $this->selector();
192 1
				break;
193
194 34
				case 'field':
195 17
					$this->_xpath = $this->field_to_xpath($this->selector());
196 17
				break;
197
198 21
				case 'label':
199 1
					$this->_xpath = $this->label_to_xpath($this->selector());
200 1
				break;
201
202 20
				case 'link':
203 9
					$this->_xpath = $this->link_to_xpath($this->selector());
204 9
				break;
205
206 14
				case 'button':
207 12
					$this->_xpath = $this->button_to_xpath($this->selector());
208 12
				break;
209
210
				default:
211 2
					throw new Exception('Locator type ":type" does not exist', array(':type' => $this->_type));
212
			}
213
		}
214
215 47
		return $this->_xpath;
216
	}
217
218
	/**
219
	 * Getter. Current type, one of css, field, xpath, label, link or button
220
	 * @return string
221
	 */
222 58
	public function type()
223
	{
224 58
		return $this->_type;
225
	}
226
227
	/**
228
	 * Getter. Current selector
229
	 * @return string
230
	 */
231 49
	public function selector()
232
	{
233 49
		return $this->_selector;
234
	}
235
236
	/**
237
	 * Getter. Current filters
238
	 * @return array
239
	 */
240 18
	public function filters()
241
	{
242 18
		return $this->_filters;
243
	}
244
245
	/**
246
	 * Convert field selector into xpath
247
	 *
248
	 * @param  string $selector
249
	 * @return string
250
	 */
251 17
	public function field_to_xpath($selector)
252
	{
253 17
		$type = "(self::input and (not(@type) or @type != 'submit')) or self::textarea or self::select";
254
255 17
		$matchers['by name']        = "@name = '$selector'";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$matchers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $matchers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
256 17
		$matchers['by id']          = "@id = '$selector'";
257 17
		$matchers['by placeholder'] = "@placeholder = '$selector'";
258 17
		$matchers['by label for']   = "@id = //label[normalize-space() = '$selector']/@for";
259 17
		$matchers['by option']      = "(self::select and ./option[(@value = \"\" or not(@value)) and contains(normalize-space(), \"$selector\")])";
260
261 17
		return "//*[($type) and (".join(' or ', $matchers).")]";
262
	}
263
264
	/**
265
	 * Convert label selector to xpath
266
	 * @param  string $selector
267
	 * @return string
268
	 */
269 1
	public function label_to_xpath($selector)
270
	{
271 1
		$type = "self::label";
272
273 1
		$matchers['by id']           = "@id = '$selector'";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$matchers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $matchers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
274 1
		$matchers['by title']        = "contains(@title, '$selector')";
275 1
		$matchers['by content text'] = "contains(normalize-space(), '$selector')";
276 1
		$matchers['by img alt']      = "descendant::img[contains(@alt, '$selector')]";
277
278 1
		return "//*[($type) and (".join(' or ', $matchers).")]";
279
	}
280
281
	/**
282
	 * Convert link selector to xpath
283
	 * @param  string $selector
284
	 * @return string
285
	 */
286 9
	public function link_to_xpath($selector)
287
	{
288 9
		$matchers['by title']        = "contains(@title, '$selector')";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$matchers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $matchers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
289 9
		$matchers['by id']           = "@id = '$selector'";
290 9
		$matchers['by content text'] = "contains(normalize-space(), '$selector')";
291 9
		$matchers['by img alt']      = "descendant::img[contains(@alt, '$selector')]";
292
293 9
		return "//a[".join(' or ', $matchers)."]";
294
	}
295
296
	/**
297
	 * Convert button selector to xpath
298
	 * @param  string $selector
299
	 * @return string
300
	 */
301 12
	public function button_to_xpath($selector)
302
	{
303 12
		$type = "(self::input and @type = 'submit') or self::button";
304
305 12
		$matchers['by title']        = "contains(@title, '$selector')";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$matchers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $matchers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
306 12
		$matchers['by id']           = "@id = '$selector'";
307 12
		$matchers['by content text'] = "contains(normalize-space(), '$selector')";
308 12
		$matchers['by img alt']      = "descendant::img[contains(@alt, '$selector')]";
309 12
		$matchers['by value']        = "contains(@value, '$selector')";
310 12
		$matchers['by name']         = "@name = '$selector'";
311
312 12
		return "//*[($type) and (".join(' or ', $matchers).")]";
313
	}
314
315
	/**
316
	 * Return a pretty printed representation of the locator
317
	 * @return string
318
	 */
319 2
	public function __toString()
320
	{
321 2
		if ($this->filters())
322
		{
323 1
			$filters = " filters: ".json_encode($this->filters());
324
		}
325
		else
326
		{
327 1
			$filters = '';
328
		}
329
330 2
		return "Locator: ({$this->type()}) {$this->selector()}".$filters;
331
	}
332
333
    /**
334
     * Convert a CSS selector to XPath.
335
     * Uses Symfony CSS Selector 2.8 and above API if possible.
336
     * Otherwise fallback to pre-2.8 static interface.
337
     *
338
     * @param  string $css_selector CSS selector
339
     * @return string XPath selector
340
     */
341 20
    private function convert_css_selector_to_xpath($css_selector)
0 ignored issues
show
Unused Code introduced by
The parameter $css_selector 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...
342
    {
343 20
        if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
344 20
            $converter = new CssSelector\CssSelectorConverter();
345 20
            return $converter->toXPath($this->selector());
346
        }
347
348
        return CssSelector\CssSelector::toXPath($this->selector());
349
    }
350
}
351