Completed
Push — master ( c9bbeb...1f0ecb )
by Ivan
03:21
created

Select::setValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.4286
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
3
namespace SP\Crawler\Element;
4
5
/**
6
 * @author    Ivan Kerin <[email protected]>
7
 * @copyright 2015, Clippings Ltd.
8
 * @license   http://spdx.org/licenses/BSD-3-Clause
9
 */
10
class Select extends AbstractElement implements InputInterface
11
{
12
    const SELECTED = './/option[@selected]';
13
    const VALUE = './/option[@value = "%s" or (not(@value) and contains(normalize-space(), "%s"))]';
14
15
    public function unselectAll()
16
    {
17
        foreach ($this->getChildren(Select::SELECTED) as $option) {
18
            $option->removeAttribute('selected');
19
        }
20
    }
21
    /**
22
     * @param string $value
23
     */
24
    public function setValue($value)
25
    {
26
        $this->unselectAll();
27
28
        $xpath = sprintf(Select::VALUE, $value, $value);
29
30
        foreach ($this->getChildren($xpath) as $option)
31
        {
32
            $option->setAttribute('selected', 'selected');
33
        }
34
    }
35
36
    /**
37
     * @return string
38
     */
39
    public function getValue()
40
    {
41
        $values = [];
42
43
        foreach ($this->getChildren(Select::SELECTED) as $option)
44
        {
45
            $values[] = $option->hasAttribute('value')
46
                ? $option->getAttribute('value')
47
                : $option->textContent;
48
        }
49
50
        return reset($values);
51
    }
52
}
53