Passed
Pull Request — master (#51)
by Sergei
22:55 queued 07:54
created

WildcardPattern::withEnding()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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