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

PathPattern::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\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 31
28 31
    /**
29 31
     * Make pattern case sensitive.
30
     *
31
     * @return self
32
     */
33
    public function caseSensitive(): self
34
    {
35
        $new = clone $this;
36 4
        $new->pattern = $this->pattern->ignoreCase(false);
37
        return $new;
38 4
    }
39 4
40 4
    /**
41
     * If path is not file or file not exists skip matching.
42
     *
43
     * @return self
44
     */
45
    public function onlyFiles(): self
46
    {
47
        $new = clone $this;
48 5
        $new->matchOnly = self::FILES;
49
        return $new;
50 5
    }
51 5
52 5
    /**
53
     * Skip matching if path is not directory or directory does no exist.
54
     *
55
     * @return self
56
     */
57
    public function onlyDirectories(): self
58
    {
59
        $new = clone $this;
60 4
        $new->matchOnly = self::DIRECTORIES;
61
        return $new;
62 4
    }
63 4
64 4
    /**
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 6
    public function match(string $path): ?bool
73
    {
74 6
        $path = str_replace('\\', '/', $path);
75 6
76 6
        if (
77
            ($this->matchOnly === self::FILES && is_dir($path)) ||
78
            ($this->matchOnly === self::DIRECTORIES && is_file($path))
79
        ) {
80
            return null;
81
        }
82
83
        return $this->pattern->match($path);
84 7
    }
85
}
86