Passed
Pull Request — master (#44)
by Alexander
03:05 queued 53s
created

CompositeMatcher::all()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Files\PathMatcher;
6
7
use InvalidArgumentException;
8
use function get_class;
9
use function is_object;
10
11
/**
12
 * Composite matcher allows combining several matchers.
13
 */
14
final class CompositeMatcher implements PathMatcherInterface
15
{
16
    private bool $matchAny;
17
18
    /**
19
     * @var array PathMatcherInterface[]
20
     */
21
    private array $matchers;
22
23 16
    private function __construct(bool $matchAny, array $matchers)
24
    {
25 16
        foreach ($matchers as $matcher) {
26 16
            if (!$matcher instanceof PathMatcherInterface) {
27 2
                $type = is_object($matcher) ? get_class($matcher) : gettype($matcher);
28 2
                $message = sprintf(
29 2
                    'Matchers should contain instances of \Yiisoft\Files\PathMatcher\PathMatcherInterface, %s given.',
30
                    $type
31
                );
32 2
                throw new InvalidArgumentException($message);
33
            }
34
        }
35 14
        $this->matchers = $matchers;
36 14
        $this->matchAny = $matchAny;
37 14
    }
38
39
    /**
40
     * Get an instance of composite matcher that gives a match if any of sub-matchers match.
41
     *
42
     * @param mixed ...$matchers Matchers to check.
43
     *
44
     * @return static
45
     */
46 8
    public static function any(...$matchers): self
47
    {
48 8
        return new self(true, $matchers);
49
    }
50
51
    /**
52
     * Get an instance of composite matcher that gives a match only if all of sub-matchers match.
53
     *
54
     * @param mixed ...$matchers Matchers to check.
55
     *
56
     * @return static
57
     */
58 8
    public static function all(...$matchers): self
59
    {
60 8
        return new self(false, $matchers);
61
    }
62
63 14
    public function match(string $path): ?bool
64
    {
65 14
        $allNulls = true;
66
67
        /** @var PathMatcherInterface $matcher */
68 14
        foreach ($this->matchers as $matcher) {
69 14
            $match = $matcher->match($path);
70
71 14
            if ($match === null) {
72 6
                continue;
73
            }
74
75 12
            $allNulls = false;
76
77 12
            if ($this->matchAny && $match) {
78 4
                return true;
79
            }
80
81 9
            if (!$this->matchAny && !$match) {
82 4
                return false;
83
            }
84
        }
85
86 6
        return $allNulls ? null : !$this->matchAny;
87
    }
88
}
89