Test Failed
Pull Request — master (#45)
by Alexander
02:09
created

PathMatcher::withNotExactSlashes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Files\PathMatcher;
6
7
use Yiisoft\Strings\StringHelper;
8
9
/**
10
 * Path matcher is based on {@see PathPattern} with the following logic:
11
 *
12
 *  1. Process `only()`. If there is at least one match, then continue, else return `false`;
13
 *  2. Process `except()`. If there is at least one match, return `false`, else continue;
14
 *  3. Process `callback()`. If there is at least one not match, return `false`, else return `true`.
15
 *
16
 * Either implementations of {@see PathMatcherInterface} or strings could be used in all above. They will be converted
17
 * {@see PathPattern} according to the options.
18
 *
19
 * If the string ends in `/`, then {@see PathPattern} will be created with {@see PathPattern::onlyDirectories()} option.
20
 * Else it will be create with {@see PathPattern::onlyFiles()} option. You can disable this behavior using
21
 * {@see PathMatcher::notCheckFilesystem()}.
22
 *
23
 * There are several other options available:
24
 *
25
 *  - {@see PathMatcher::caseSensitive()} makes string patterns case sensitive;
26
 *  - {@see PathMatcher::withFullPath()} string patterns will be matched as full path, not just as ending of the path;
27
 *  - {@see PathMatcher::withNotExactSlashes()} match `/` character with wildcards in string patterns.
28
 *
29
 * Usage example:
30
 *
31
 * ```php
32
 * $matcher = (new PathMatcher())
33
 *     ->notCheckFilesystem()
34
 *     ->only('*.css', '*.js')
35
 *     ->except('theme.css');
36
 *
37
 * $matcher->match('/var/www/example.com/assets/css/main.css'); // true
38
 * $matcher->match('/var/www/example.com/assets/css/main.css.map'); // false
39
 * $matcher->match('/var/www/example.com/assets/css/theme.css'); // false
40
 * ```
41
 */
42
final class PathMatcher implements PathMatcherInterface
43
{
44
    /**
45
     * @var PathMatcherInterface[]|null
46
     */
47
    private ?array $only = null;
48
49
    /**
50
     * @var PathMatcherInterface[]|null
51
     */
52
    private ?array $except = null;
53
54
    /**
55
     * @var callable[]|null
56
     */
57
    private ?array $callbacks = null;
58
59
    private bool $caseSensitive = false;
60
    private bool $checkFilesystem = true;
61
62
    /**
63
     * Make string patterns case sensitive.
64
     * Note: applies only to string patterns.
65
     *
66
     * @return self
67
     */
68
    public function caseSensitive(): self
69
    {
70 2
        $new = clone $this;
71
        $new->caseSensitive = true;
72 2
        return $new;
73 2
    }
74 2
75
    /**
76
     * Match path only as string, do not check if file or directory exists.
77
     * Note: applies only to string patterns.
78
     *
79
     * @return self
80
     */
81
    public function doNotCheckFilesystem(): self
82
    {
83 2
        $new = clone $this;
84
        $new->checkFilesystem = false;
85 2
        return $new;
86 2
    }
87 2
88
    /**
89
     * Set list of patterns that the files or directories should match.
90
     *
91
     * @param PathMatcherInterface|string ...$patterns
92
     *
93
     * @return self
94
     */
95
    public function only(...$patterns): self
96 2
    {
97
        $new = clone $this;
98 2
        $new->only = $this->prepareMatchers($patterns);
99 2
        return $new;
100 2
    }
101
102
    /**
103
     * Set list of patterns that the files or directories should not match.
104
     *
105
     * @param PathMatcherInterface|string ...$patterns
106
     *
107
     * @return self
108
     */
109 11
    public function except(...$patterns): self
110
    {
111 11
        $new = clone $this;
112 11
        $new->except = $this->prepareMatchers($patterns);
113 11
        return $new;
114
    }
115
116
    /**
117
     * Set list of PHP callbacks that are called for each path.
118
     *
119
     * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
120
     * The callback should return `true` if there is a match and `false` otherwise.
121
     *
122
     * @param callable ...$callbacks
123 12
     *
124
     * @return self
125 12
     */
126 12
    public function callback(callable ...$callbacks): self
127 12
    {
128
        $new = clone $this;
129
        $new->callbacks = $callbacks;
130
        return $new;
131
    }
132
133
    /**
134
     * Checks if the passed path match specified conditions.
135
     *
136
     * @param string $path The tested path.
137 6
     *
138
     * @return bool Whether the path matches conditions or not.
139 6
     */
140 6
    public function match(string $path): bool
141 6
    {
142
        if (!$this->matchOnly($path)) {
143
            return false;
144
        }
145
146
        if ($this->matchExcept($path)) {
147
            return false;
148
        }
149
150
        if ($this->callbacks !== null) {
151
            foreach ($this->callbacks as $callback) {
152
                if (!$callback($path)) {
153
                    return false;
154 2
                }
155
            }
156 2
        }
157 2
158 2
        return true;
159
    }
160
161
    private function matchOnly(string $path): bool
162
    {
163
        if ($this->only === null) {
164
            return true;
165
        }
166
167
        $hasFalse = false;
168 16
        $hasNull = false;
169
170 16
        foreach ($this->only as $pattern) {
171 10
            if ($pattern->match($path) === true) {
172
                return true;
173
            }
174 16
            if ($pattern->match($path) === false) {
175 5
                $hasFalse = true;
176
            }
177
            if ($pattern->match($path) === null) {
178 16
                $hasNull = true;
179 1
            }
180 1
        }
181 1
182
        if ($this->checkFilesystem) {
183
            if (is_file($path)) {
184
                return !$hasFalse;
185
            }
186 15
            if (is_dir($path)) {
187
                return $hasNull;
188
            }
189 16
        }
190
191 16
        return false;
192 5
    }
193
194
    private function matchExcept(string $path): bool
195 11
    {
196 11
        if ($this->except === null) {
197
            return false;
198 11
        }
199 11
200 10
        foreach ($this->except as $pattern) {
201
            if ($pattern->match($path) === true) {
202 10
                return true;
203 10
            }
204
        }
205 10
206 4
        return false;
207
    }
208
209
    /**
210 10
     * @param PathMatcherInterface[]|string[] $patterns
211 5
     *
212 4
     * @return PathMatcherInterface[]
213
     */
214 5
    private function prepareMatchers(array $patterns): array
215 5
    {
216
        $pathPatterns = [];
217
        foreach ($patterns as $pattern) {
218
            if ($pattern instanceof PathMatcherInterface) {
219 6
                $pathPatterns[] = $pattern;
220
                continue;
221
            }
222 16
223
            $isDirectoryPattern = StringHelper::endsWith($pattern, '/');
224 16
            if ($isDirectoryPattern) {
225 11
                $pattern = StringHelper::substring($pattern, 0, -1);
226
            }
227
228 5
            $pathPattern = new PathPattern($pattern);
229 5
230 5
            if ($this->caseSensitive) {
231
                $pathPattern = $pathPattern->caseSensitive();
232
            }
233
234 5
            if ($this->checkFilesystem) {
235
                $pathPattern = $isDirectoryPattern
236
                    ? $pathPattern->onlyDirectories()
237
                    : $pathPattern->onlyFiles();
238
            }
239
240
            $pathPatterns[] = $pathPattern;
241
        }
242 15
        return $pathPatterns;
243
    }
244
}
245