Passed
Pull Request — master (#39)
by Alexander
01:11
created

WildcardPattern::match()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 22
c 1
b 0
f 0
nc 9
nop 1
dl 0
loc 35
ccs 14
cts 14
cp 1
crap 6
rs 8.9457
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Strings;
6
7
/**
8
 * A shell wildcard pattern to match strings against.
9
 *
10
 * - `\` escapes other special characters if usage of escape character is not turned off.
11
 * - `*` matches any string, including the empty string.
12
 * - `?` matches any single character.
13
 * - `[seq]` matches any character in seq.
14
 * - `[a-z]` matches any character from a to z.
15
 * - `[!seq]` matches any character not in seq.
16
 * - `[[:alnum:]]` matches POSIX style character classes,
17
 *   see {@see https://www.php.net/manual/en/regexp.reference.character-classes.php}.
18
 *
19
 * @see https://www.man7.org/linux/man-pages/man7/glob.7.html
20
 *
21
 * The class emulates {@see fnmatch()} using PCRE since it is not uniform across operating systems
22
 * and may not be available.
23
 */
24
final class WildcardPattern
25
{
26
    private bool $withoutEscape = false;
27
    private bool $matchSlashesExactly = false;
28
    private bool $matchLeadingPeriodExactly = false;
29
    private bool $ignoreCase = false;
30
    private string $pattern;
31
32
    /**
33
     * @param string $pattern The shell wildcard pattern to match against.
34
     */
35 54
    public function __construct(string $pattern)
36
    {
37 54
        $this->pattern = $pattern;
38 54
    }
39
40
    /**
41
     * Checks if the passed string would match the given shell wildcard pattern.
42
     *
43
     * @param string $string The tested string.
44
     * @return bool Whether the string matches pattern or not.
45
     */
46 54
    public function match(string $string): bool
47
    {
48 54
        if ($this->pattern === '*' && !$this->matchSlashesExactly) {
49 2
            return true;
50
        }
51
52
        $replacements = [
53 52
            '\\\\\\\\' => '\\\\',
54
            '\\\\\\*' => '[*]',
55
            '\\\\\\?' => '[?]',
56
            '\*' => '.*',
57
            '\?' => '.',
58
            '\[\!' => '[^',
59
            '\[' => '[',
60
            '\]' => ']',
61
            '\-' => '-',
62
        ];
63
64 52
        if ($this->withoutEscape) {
65 5
            unset($replacements['\\\\\\\\'], $replacements['\\\\\\*'], $replacements['\\\\\\?']);
66
        }
67
68 52
        if ($this->matchSlashesExactly) {
69 10
            $replacements['\*'] = '[^/\\\\]*';
70 10
            $replacements['\?'] = '[^/\\\\]';
71
        }
72
73 52
        $pattern = strtr(preg_quote($this->pattern, '#'), $replacements);
74 52
        $pattern = '#^' . $pattern . '$#us';
75
76 52
        if ($this->ignoreCase) {
77 1
            $pattern .= 'i';
78
        }
79
80 52
        return preg_match($pattern, $string) === 1;
81
    }
82
83
    /**
84
     * Disables using `\` to escape following special character. `\` becomes regular character.
85
     * @return self
86
     */
87 5
    public function withoutEscape(): self
88
    {
89 5
        $new = clone $this;
90 5
        $new->withoutEscape = true;
91 5
        return $new;
92
    }
93
94
    /**
95
     * Do not match `/` character with wildcards. The only way to match `/` is with an explicit `/` in pattern.
96
     * Useful for matching file paths. Use with {@see withExactLeadingPeriod()}.
97
     * @return self
98
     */
99 10
    public function withExactSlashes(): self
100
    {
101 10
        $new = clone $this;
102 10
        $new->matchSlashesExactly = true;
103 10
        return $new;
104
    }
105
106
    /**
107
     * Make pattern case insensitive.
108
     * @return self
109
     */
110 1
    public function ignoreCase(): self
111
    {
112 1
        $new = clone $this;
113 1
        $new->ignoreCase = true;
114 1
        return $new;
115
    }
116
117
    /**
118
     * Do not match `.` character at the beginning of string with wildcards.
119
     * Useful for matching file paths. Use with {@see withExactSlashes()}.
120
     * @return self
121
     */
122
    public function withExactLeadingPeriod(): self
123
    {
124
        $new = clone $this;
125
        $new->matchLeadingPeriodExactly = true;
126
        return $new;
127
    }
128
}
129