Quoter::pregUnQuote()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 0
cts 10
cp 0
rs 9.344
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
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 implements QuoterInterface
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
     *
32
     * @throws \UnexpectedValueException
33
     *
34
     * @return string
35
     */
36
    public function pregUnQuote(string $pattern) : string
37
    {
38
        // Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement
39
        if (!preg_match('/[^a-z\s]/i', $pattern)) {
40
            return $pattern;
41
        }
42
43
        $origPattern = $pattern;
44
45
        // Undo the \\x replacement, that is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
46
        // @source https://github.com/browscap/browscap-php
47
        $pattern = preg_replace(
48
            ['/(?<!\\\\)\\.\\*/', '/(?<!\\\\)\\./', '/(?<!\\\\)\\\\x/'],
49
            ['\\*', '\\?', '\\x'],
50
            $pattern
51
        );
52
53
        if (null === $pattern) {
54
            throw new \UnexpectedValueException(
55
                sprintf('an error occured while handling pattern %s', $origPattern)
56
            );
57
        }
58
59
        // Undo preg_quote
60
        return str_replace(
61
            [
62
                '\\\\', '\\+', '\\*', '\\?', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=',
63
                '\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '\\.', '\\/',
64
            ],
65
            [
66
                '\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':',
67
                '-', '.', '/',
68
            ],
69
            $pattern
70
        );
71
    }
72
}
73