Expression   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 9
c 2
b 1
f 1
lcom 1
cbo 0
dl 0
loc 90
ccs 17
cts 17
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getRaw() 0 4 1
A build() 0 14 2
A contained() 0 4 1
A contains() 0 4 1
A getPattern() 0 5 2
A __toString() 0 4 1
1
<?php
2
3
namespace Bee4\RobotsTxt;
4
5
/**
6
 * Class Expression
7
 * Represent a matching expression rule
8
 *
9
 * @copyright Bee4 2016
10
 * @author    Stephane HULARD <[email protected]>
11
 */
12
class Expression
13
{
14
    /**
15
     * Raw definition
16
     * @var string
17
     */
18
    private $raw;
19
20
    /**
21
     * Rule pattern
22
     * @var string
23
     */
24
    private $pattern;
25
26
    /**
27
     * Initialize expression
28
     * @param string $rule
29
     */
30
    public function __construct($rule)
31
    {
32 1
        $this->raw = $rule;
33 1
    }
34
35
    /**
36
     * Retrieve the raw rule definition
37
     * @return string
38
     */
39
    public function getRaw()
40
    {
41 1
        return $this->raw;
42
    }
43
44
    /**
45
     * Transform current pattern to be used for matching
46
     * @return string
47
     */
48
    private function build()
49
    {
50 1
        $raw = $this->raw;
51
52 1
        $ended = substr($raw, -1) === '$';
53 1
        $raw = rtrim($raw, '*');
54 1
        $raw = rtrim($raw, '$');
55
56 1
        $parts = explode('*', $raw);
57 1
        array_walk($parts, function (&$part) {
58 1
            $part = preg_quote($part, '/');
59 1
        });
60 1
        return implode('.*', $parts).($ended?'':'.*');
61
    }
62
63
    /**
64
     * Check if current expression is contained in another
65
     * @param  Expression $exp
66
     * @return boolean
67
     */
68
    public function contained(Expression $exp)
69
    {
70 1
        return $exp->contains($this);
71
    }
72
73
    /**
74
     * Check if current expression contains another
75
     * @param  Expression $exp
76
     * @return boolean
77
     */
78
    public function contains(Expression $exp)
79
    {
80 1
        return preg_match('/^'.(string)$this.'$/', $exp->getRaw()) === 1;
81
    }
82
83
    /**
84
     * Retrieve the regex pattern corresponding to the Expression
85
     * @return string
86
     */
87
    public function getPattern()
88
    {
89 1
        $this->pattern = $this->pattern ?: $this->build();
90 1
        return $this->pattern;
91
    }
92
93
    /**
94
     * Transform expression to string
95
     * @return string
96
     */
97
    public function __toString()
98
    {
99 1
        return $this->getPattern();
100
    }
101
}
102