Completed
Push — master ( 82eb41...4f6b0a )
by Alexander
03:49
created

Glob::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace Xiag\Rql\Parser;
3
4
class Glob
5
{
6
    /**
7
     * @var string
8
     */
9
    private $glob;
10
11
    /**
12
     * @param string $glob
13
     */
14 32
    public function __construct($glob)
15
    {
16 32
        $this->glob = $glob;
17 32
    }
18
19
    /**
20
     * Encode raw string value
21
     *
22
     * @param string $value
23
     * @return string
24
     */
25 30
    public static function encode($value)
26
    {
27 30
        return addcslashes($value, '\?*');
28
    }
29
30
    /**
31
     * Returns raw glob
32
     *
33
     * @return string
34
     */
35 7
    public function __toString()
36
    {
37 7
        return $this->glob;
38
    }
39
40
    /**
41
     * Returns RQL representation
42
     *
43
     * @return string
44
     */
45 7
    public function toRql()
46
    {
47 7
        return $this->decoder(
48 7
            '*',
49 7
            '?',
50
            function ($char) {
51 5
                return strtr(rawurlencode($char), [
52 5
                    '-' => '%2D',
53 5
                    '_' => '%5F',
54 5
                    '.' => '%2E',
55 5
                    '~' => '%7E',
56 5
                ]);
57
            }
58 7
        );
59
    }
60
61
    /**
62
     * Returns RegExp representation
63
     *
64
     * @return string
65
     */
66 7
    public function toRegex()
67
    {
68 7
        $regex = $this->decoder(
69 7
            '.*',
70 7
            '.',
71
            function ($char) {
72 5
                return preg_quote($char, '/');
73
            }
74 7
        );
75
76 7
        return '^' . $regex . '$';
77
    }
78
79
    /**
80
     * Returns LIKE representation
81
     *
82
     * @return string
83
     */
84 7
    public function toLike()
85
    {
86 7
        return $this->decoder(
87 7
            '%',
88 7
            '_',
89
            function ($char) {
90 5
                return addcslashes($char, '\%_');
91
            }
92 7
        );
93
    }
94
95 21
    private function decoder($many, $one, callable $escaper)
96
    {
97 21
        return preg_replace_callback(
98 21
            '/\\\\.|\*|\?|./',
99 21
            function ($match) use ($many, $one, $escaper) {
100 21
                if ($match[0] === '*') {
101 6
                    return $many;
102 18
                } elseif ($match[0] === '?') {
103 6
                    return $one;
104
                } else {
105 15
                    return $escaper(stripslashes($match[0]));
106
                }
107 21
            },
108 21
            $this->glob
109 21
        );
110
    }
111
}
112