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

CssOrXpathExpressionTranslator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 2
cbo 2
dl 0
loc 52
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getTranslator() 0 7 2
A convertToXpath() 0 18 5
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
}