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

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