Filter::__construct()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace loophp\phptree\Modifier;
11
12
use loophp\phptree\Node\NodeInterface;
13
use loophp\phptree\Traverser\PostOrder;
14
use loophp\phptree\Traverser\PreOrder;
15
use loophp\phptree\Traverser\TraverserInterface;
16
17
/**
18
 * Class Filter.
19
 */
20
class Filter implements ModifierInterface
21
{
22
    /**
23
     * @var callable
24
     */
25
    private $filter;
26
27
    /**
28
     * @var PreOrder|TraverserInterface
29
     */
30
    private $traverser;
31
32
    /**
33
     * Filter constructor.
34
     */
35 2
    public function __construct(callable $filter, ?TraverserInterface $traverser = null)
36
    {
37 2
        $this->filter = $filter;
38 2
        $this->traverser = $traverser ?? new PostOrder();
39 2
    }
40
41 1
    public function modify(NodeInterface $tree): NodeInterface
42
    {
43 1
        foreach ($this->traverser->traverse($tree) as $item) {
44 1
            if (null === $parent = $item->getParent()) {
45 1
                continue;
46
            }
47
48 1
            if (!(bool) ($this->filter)($item)) {
49 1
                continue;
50
            }
51
52 1
            $parent->remove($item);
53
        }
54
55 1
        return $tree;
56
    }
57
}
58