Passed
Push — master ( d3d965...60dd66 )
by Alexander
02:44 queued 36s
created

PathMatcher::withFullPath()   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 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 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 11
    public function doNotCheckFilesystem(): self
82
    {
83 11
        $new = clone $this;
84 11
        $new->checkFilesystem = false;
85 11
        return $new;
86
    }
87
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 12
    public function only(...$patterns): self
96
    {
97 12
        $new = clone $this;
98 12
        $new->only = $this->prepareMatchers($patterns);
99 12
        return $new;
100
    }
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 6
    public function except(...$patterns): self
110
    {
111 6
        $new = clone $this;
112 6
        $new->except = $this->prepareMatchers($patterns);
113 6
        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
     *
124
     * @return self
125
     */
126 2
    public function callback(callable ...$callbacks): self
127
    {
128 2
        $new = clone $this;
129 2
        $new->callbacks = $callbacks;
130 2
        return $new;
131
    }
132
133
    /**
134
     * Checks if the passed path match specified conditions.
135
     *
136
     * @param string $path The tested path.
137
     *
138
     * @return bool Whether the path matches conditions or not.
139
     */
140 16
    public function match(string $path): bool
141
    {
142 16
        if (!$this->matchOnly($path)) {
143 10
            return false;
144
        }
145
146 16
        if ($this->matchExcept($path)) {
147 5
            return false;
148
        }
149
150 16
        if ($this->callbacks !== null) {
151 1
            foreach ($this->callbacks as $callback) {
152 1
                if (!$callback($path)) {
153 1
                    return false;
154
                }
155
            }
156
        }
157
158 15
        return true;
159
    }
160
161 16
    private function matchOnly(string $path): bool
162
    {
163 16
        if ($this->only === null) {
164 5
            return true;
165
        }
166
167 11
        $hasFalse = false;
168 11
        $hasNull = false;
169
170 11
        foreach ($this->only as $pattern) {
171 11
            if ($pattern->match($path) === true) {
172 10
                return true;
173
            }
174 10
            if ($pattern->match($path) === false) {
175 10
                $hasFalse = true;
176
            }
177 10
            if ($pattern->match($path) === null) {
178 4
                $hasNull = true;
179
            }
180
        }
181
182 10
        if ($this->checkFilesystem) {
183 5
            if (is_file($path)) {
184 4
                return !$hasFalse;
185
            }
186 5
            if (is_dir($path)) {
187 5
                return $hasNull;
188
            }
189
        }
190
191 6
        return false;
192
    }
193
194 16
    private function matchExcept(string $path): bool
195
    {
196 16
        if ($this->except === null) {
197 11
            return false;
198
        }
199
200 5
        foreach ($this->except as $pattern) {
201 5
            if ($pattern->match($path) === true) {
202 5
                return true;
203
            }
204
        }
205
206 5
        return false;
207
    }
208
209
    /**
210
     * @param PathMatcherInterface[]|string[] $patterns
211
     *
212
     * @return PathMatcherInterface[]
213
     */
214 15
    private function prepareMatchers(array $patterns): array
215
    {
216 15
        $pathPatterns = [];
217 15
        foreach ($patterns as $pattern) {
218 15
            if ($pattern instanceof PathMatcherInterface) {
219
                $pathPatterns[] = $pattern;
220
                continue;
221
            }
222
223 15
            $isDirectoryPattern = StringHelper::endsWith($pattern, '/');
224 15
            if ($isDirectoryPattern) {
225 7
                $pattern = StringHelper::substring($pattern, 0, -1);
226
            }
227
228 15
            $pathPattern = new PathPattern($pattern);
229
230 15
            if ($this->caseSensitive) {
231 1
                $pathPattern = $pathPattern->caseSensitive();
232
            }
233
234 15
            if ($this->checkFilesystem) {
235 8
                $pathPattern = $isDirectoryPattern
236 6
                    ? $pathPattern->onlyDirectories()
237 8
                    : $pathPattern->onlyFiles();
238
            }
239
240 15
            $pathPatterns[] = $pathPattern;
241
        }
242 15
        return $pathPatterns;
243
    }
244
}
245