SimpleFilterChain::appendFilter()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
nc 1
nop 1
dl 0
loc 4
c 0
b 0
f 0
cc 1
rs 10
ccs 3
cts 3
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DanBettles\Gestalt;
6
7
use const false;
8
use const null;
9
10
/**
11
 * A simple unidirectional filter chain.
12
 */
13
class SimpleFilterChain
14
{
15
    private $filters;
16
17 27
    public function __construct(array $filters = [])
18
    {
19 27
        $this->setFilters($filters);
20
    }
21
22 13
    public function appendFilter(callable $filter): self
23
    {
24 13
        $this->filters[] = $filter;
25 13
        return $this;
26
    }
27
28 27
    private function setFilters(array $filters): self
29
    {
30 27
        $this->filters = [];
31
32 27
        foreach ($filters as $filter) {
33 12
            $this->appendFilter($filter);
34
        }
35
36 21
        return $this;
37
    }
38
39 14
    public function getFilters(): array
40
    {
41 14
        return $this->filters;
42
    }
43
44
    /**
45
     * Invokes each filter in turn; the specified 'request' will be passed to each filter.
46
     *
47
     * Iteration will stop if a filter returns the value of `$valueToBreak`.  If iteration is forcibly stopped then the
48
     * method will return the value of `$valueToBreak`.  If, however, iteration is allowed to continue until completion
49
     * then the method will return `null`.
50
     *
51
     * @param mixed $request
52
     * @param mixed $valueToBreak
53
     * @return mixed
54
     */
55 4
    public function execute(&$request, $valueToBreak = false)
56
    {
57 4
        foreach ($this->getFilters() as $filter) {
58 4
            $returnValue = $filter($request);
59
60 4
            if ($valueToBreak === $returnValue) {
61 2
                return $returnValue;
62
            }
63
        }
64
65 2
        return null;
66
    }
67
}
68