Completed
Push — master ( 41d47b...c28fef )
by James
10s
created

Quoter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 21.43%

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 53
ccs 3
cts 14
cp 0.2143
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A pregQuote() 0 7 1
B pregUnQuote() 0 28 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace BrowscapPHP\Helper;
5
6
/**
7
 * class to help quoting strings for using a regex
8
 */
9
final class Quoter
10
{
11
    /**
12
     * Converts browscap match patterns into preg match patterns.
13
     *
14
     * @param string $user_agent
15
     * @param string $delimiter
16
     *
17
     * @return string
18
     */
19 1
    public function pregQuote(string $user_agent, string $delimiter = '/') : string
20
    {
21 1
        $pattern = preg_quote($user_agent, $delimiter);
22
23
        // the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
24 1
        return str_replace(['\*', '\?', '\\x'], ['.*', '.', '\\\\x'], $pattern);
25
    }
26
27
    /**
28
     * Reverts the quoting of a pattern.
29
     *
30
     * @param  string $pattern
31
     * @return string
32
     */
33
    public function pregUnQuote(string $pattern) : string
34
    {
35
        // Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement
36
        if (preg_match('/[^a-z\s]/i', $pattern)) {
37
            // Undo the \\x replacement, that is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
38
            // @source https://github.com/browscap/browscap-php
39
            $pattern = preg_replace(
40
                ['/(?<!\\\\)\\.\\*/', '/(?<!\\\\)\\./', '/(?<!\\\\)\\\\x/'],
41
                ['\\*', '\\?', '\\x'],
42
                $pattern
43
            );
44
45
            // Undo preg_quote
46
            $pattern = str_replace(
47
                [
48
                    '\\\\', '\\+', '\\*', '\\?', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=',
49
                    '\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '\\.', '\\/',
50
                ],
51
                [
52
                    '\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':',
53
                    '-', '.', '/',
54
                ],
55
                $pattern
56
            );
57
        }
58
59
        return $pattern;
60
    }
61
}
62