Completed
Push — master ( 0c0c0a...b9a066 )
by Shcherbak
25s queued 10s
created

CssOrXpathExpressionTranslator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xparse\CssExpressionTranslator;
6
7
use Xparse\ExpressionTranslator\ExpressionTranslatorInterface;
8
9
/**
10
 * Automatically detect xpath or css query language and convert it to the xpath
11
 *
12
 * @author Ivan Shcherbak <[email protected]>
13
 */
14
class CssOrXpathExpressionTranslator implements ExpressionTranslatorInterface
15
{
16
17
    /**
18
     * @var ExpressionTranslatorInterface
19
     */
20
    private static $translator;
21
22
    /**
23
     * @var ExpressionTranslatorInterface
24
     */
25
    private $cssTranslator;
26
27
28
    /**
29
     * @param ExpressionTranslatorInterface $cssTranslator
30
     */
31 1
    public function __construct(ExpressionTranslatorInterface $cssTranslator)
32
    {
33 1
        $this->cssTranslator = $cssTranslator;
34 1
    }
35
36
37 19
    public static function getTranslator(): ExpressionTranslatorInterface
38
    {
39 19
        if (self::$translator === null) {
40 1
            self::$translator = new CssOrXpathExpressionTranslator(new CssExpressionTranslator());
41
        }
42 19
        return self::$translator;
43
    }
44
45
46 19
    public function convertToXpath(string $expression): string
47
    {
48 19
        $expression = trim($expression);
49 19
        if ($expression === '') {
50 2
            throw new \InvalidArgumentException('Expect not empty expression');
51
        }
52 17
        if ($expression === '.') {
53 1
            return $expression;
54
        }
55 16
        if (strpos($expression, './') === 0) {
56 2
            return $expression;
57
        }
58 14
        $firstChar = substr($expression, 0, 1);
59 14
        if (in_array($firstChar, ['/', '('])) {
60 4
            return $expression;
61
        }
62 10
        return $this->cssTranslator->convertToXpath($expression);
63
    }
64
65
}