|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Files\PathMatcher; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Strings\WildcardPattern; |
|
8
|
|
|
|
|
9
|
|
|
use function is_dir; |
|
10
|
|
|
use function is_file; |
|
11
|
|
|
use function str_replace; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* A shell path pattern to match against. Based on {@see WildcardPattern}. |
|
15
|
|
|
*/ |
|
16
|
|
|
final class PathPattern implements PathMatcherInterface |
|
17
|
|
|
{ |
|
18
|
|
|
private const FILES = 1; |
|
19
|
|
|
private const DIRECTORIES = 2; |
|
20
|
|
|
|
|
21
|
|
|
private WildcardPattern $pattern; |
|
22
|
|
|
private ?int $matchOnly = null; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param string $pattern The path pattern to match against. |
|
26
|
|
|
*/ |
|
27
|
33 |
|
public function __construct(string $pattern) |
|
28
|
|
|
{ |
|
29
|
33 |
|
$this->pattern = (new WildcardPattern($pattern))->ignoreCase(); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Make pattern case sensitive. |
|
34
|
|
|
*/ |
|
35
|
4 |
|
public function caseSensitive(): self |
|
36
|
|
|
{ |
|
37
|
4 |
|
$new = clone $this; |
|
38
|
4 |
|
$new->pattern = $this->pattern->ignoreCase(false); |
|
39
|
4 |
|
return $new; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* If path is not file or file not exists skip matching. |
|
44
|
|
|
*/ |
|
45
|
7 |
|
public function onlyFiles(): self |
|
46
|
|
|
{ |
|
47
|
7 |
|
$new = clone $this; |
|
48
|
7 |
|
$new->matchOnly = self::FILES; |
|
49
|
7 |
|
return $new; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Skip matching if path is not directory or directory does no exist. |
|
54
|
|
|
*/ |
|
55
|
8 |
|
public function onlyDirectories(): self |
|
56
|
|
|
{ |
|
57
|
8 |
|
$new = clone $this; |
|
58
|
8 |
|
$new->matchOnly = self::DIRECTORIES; |
|
59
|
8 |
|
return $new; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Checks if the passed path would match the given shell path pattern. |
|
64
|
|
|
* If need match only files and path is directory or conversely then matching skipped and returned `null`. |
|
65
|
|
|
* |
|
66
|
|
|
* @param string $path The tested path. |
|
67
|
|
|
* |
|
68
|
|
|
* @return bool|null Whether the path matches pattern or not, `null` if matching skipped. |
|
69
|
|
|
*/ |
|
70
|
31 |
|
public function match(string $path): ?bool |
|
71
|
|
|
{ |
|
72
|
31 |
|
$path = str_replace('\\', '/', $path); |
|
73
|
|
|
|
|
74
|
|
|
if ( |
|
75
|
31 |
|
($this->matchOnly === self::FILES && is_dir($path)) || |
|
76
|
31 |
|
($this->matchOnly === self::DIRECTORIES && is_file($path)) |
|
77
|
|
|
) { |
|
78
|
5 |
|
return null; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
31 |
|
return $this->pattern->match($path); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|