Passed
Push — master ( decfe3...89c5df )
by Alexander
18:16 queued 16:56
created

WildcardPattern::match()   B

Complexity

Conditions 9
Paths 33

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 25
c 1
b 0
f 0
nc 33
nop 1
dl 0
loc 41
ccs 17
cts 17
cp 1
crap 9
rs 8.0555
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 bool $matchEnding = false;
31
    private string $pattern;
32
33
    /**
34
     * @param string $pattern The shell wildcard pattern to match against.
35
     */
36 67
    public function __construct(string $pattern)
37
    {
38 67
        $this->pattern = $pattern;
39 67
    }
40
41
    /**
42
     * Checks if the passed string would match the given shell wildcard pattern.
43
     *
44
     * @param string $string The tested string.
45
     * @return bool Whether the string matches pattern or not.
46
     */
47 66
    public function match(string $string): bool
48
    {
49 66
        if ($this->pattern === '*' && !$this->matchSlashesExactly && !$this->matchLeadingPeriodExactly) {
50 2
            return true;
51
        }
52
53 64
        $pattern = $this->pattern;
54
55 64
        if ($this->matchLeadingPeriodExactly) {
56 3
            $pattern = preg_replace('/^[*?]/', '[!.]', $pattern);
57
        }
58
59
        $replacements = [
60 64
            '\\\\\\\\' => '\\\\',
61
            '\\\\\\*' => '[*]',
62
            '\\\\\\?' => '[?]',
63
            '\*' => '.*',
64
            '\?' => '.',
65
            '\[\!' => '[^',
66
            '\[' => '[',
67
            '\]' => ']',
68
            '\-' => '-',
69
        ];
70
71 64
        if ($this->withoutEscape) {
72 5
            unset($replacements['\\\\\\\\'], $replacements['\\\\\\*'], $replacements['\\\\\\?']);
73
        }
74
75 64
        if ($this->matchSlashesExactly) {
76 13
            $replacements['\*'] = '[^/\\\\]*';
77 13
            $replacements['\?'] = '[^/\\\\]';
78
        }
79
80 64
        $pattern = strtr(preg_quote($pattern, '#'), $replacements);
81 64
        $pattern = '#' . ($this->matchEnding ? '' : '^') . $pattern . '$#us';
82
83 64
        if ($this->ignoreCase) {
84 1
            $pattern .= 'i';
85
        }
86
87 64
        return preg_match($pattern, $string) === 1;
88
    }
89
90
    /**
91
     * Disables using `\` to escape following special character. `\` becomes regular character.
92
     * @param bool $flag
93
     * @return self
94
     */
95 7
    public function withoutEscape(bool $flag = true): self
96
    {
97 7
        $new = clone $this;
98 7
        $new->withoutEscape = $flag;
99 7
        return $new;
100
    }
101
102
    /**
103
     * Do not match `/` character with wildcards. The only way to match `/` is with an explicit `/` in pattern.
104
     * Useful for matching file paths. Use with {@see withExactLeadingPeriod()}.
105
     * @param bool $flag
106
     * @return self
107
     */
108 15
    public function withExactSlashes(bool $flag = true): self
109
    {
110 15
        $new = clone $this;
111 15
        $new->matchSlashesExactly = $flag;
112 15
        return $new;
113
    }
114
115
    /**
116
     * Make pattern case insensitive.
117
     * @param bool $flag
118
     * @return self
119
     */
120 3
    public function ignoreCase(bool $flag = true): self
121
    {
122 3
        $new = clone $this;
123 3
        $new->ignoreCase = $flag;
124 3
        return $new;
125
    }
126
127
    /**
128
     * Do not match `.` character at the beginning of string with wildcards.
129
     * Useful for matching file paths. Use with {@see withExactSlashes()}.
130
     * @param bool $flag
131
     * @return self
132
     */
133 5
    public function withExactLeadingPeriod(bool $flag = true): self
134
    {
135 5
        $new = clone $this;
136 5
        $new->matchLeadingPeriodExactly = $flag;
137 5
        return $new;
138
    }
139
140
    /**
141
     * Match ending only.
142
     * By default wildcard pattern matches string exactly. By using this mode, beginning of the string could be anything.
143
     * @param bool $flag
144
     * @return self
145
     */
146 8
    public function withEnding(bool $flag = true): self
147
    {
148 8
        $new = clone $this;
149 8
        $new->matchEnding = $flag;
150 8
        return $new;
151
    }
152
}
153