Passed
Pull Request — master (#22)
by Sergei
01:58
created

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