Completed
Push — master ( 3b3c4b...78d589 )
by Lars
01:33
created

SelectorConverter::toXPath()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8.0093

Importance

Changes 0
Metric Value
cc 8
nc 8
nop 2
dl 0
loc 40
ccs 18
cts 19
cp 0.9474
crap 8.0093
rs 8.0355
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
use Symfony\Component\CssSelector\CssSelectorConverter;
8
9
class SelectorConverter
10
{
11
    /**
12
     * @var string[]
13
     *
14
     * @phpstan-var array<string,string>
15
     */
16
    protected static $compiled = [];
17
18
    /**
19
     * @param string $selector
20
     * @param bool $ignoreCssSelectorErrors
21
     *                                      <p>
22
     *                                      Ignore css selector errors and use the $selector as it is on error,
23
     *                                      so that you can also use xPath selectors.
24
     *                                      </p>
25
     *
26
     * @return string
27
     */
28 154
    public static function toXPath(string $selector, bool $ignoreCssSelectorErrors = false)
29
    {
30 154
        if (isset(self::$compiled[$selector])) {
31 94
            return self::$compiled[$selector];
32
        }
33
34
        // Select DOMText
35 94
        if ($selector === 'text') {
36 3
            return '//text()';
37
        }
38
39
        // Select DOMComment
40 91
        if ($selector === 'comment') {
41 2
            return '//comment()';
42
        }
43
44 89
        if (\strpos($selector, '//') === 0) {
45 11
            return $selector;
46
        }
47
48 80
        if (!\class_exists(CssSelectorConverter::class)) {
49
            throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector 2.8+ is not installed (you can use filterXPath instead).');
50
        }
51
52 80
        $converter = new CssSelectorConverter(true);
53
54 80
        if ($ignoreCssSelectorErrors) {
55
            try {
56 4
                $xPathQuery = $converter->toXPath($selector);
57 1
            } catch (\Exception $e) {
58 4
                $xPathQuery = $selector;
59
            }
60
        } else {
61 76
            $xPathQuery = $converter->toXPath($selector);
62
        }
63
64 80
        self::$compiled[$selector] = $xPathQuery;
65
66 80
        return $xPathQuery;
67
    }
68
}
69