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

CompositeMatcher   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 73
ccs 26
cts 26
cp 1
rs 10
wmc 14

4 Methods

Rating   Name   Duplication   Size   Complexity  
B match() 0 24 8
A any() 0 3 1
A all() 0 3 1
A __construct() 0 14 4
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