Skip to content

Commit c20db13

Browse files
committed
Add new Filter modifier.
1 parent 24e6d45 commit c20db13

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace spec\loophp\phptree\Modifier;
6+
7+
use loophp\phptree\Modifier\Filter;
8+
use loophp\phptree\Node\ValueNode;
9+
use loophp\phptree\Node\ValueNodeInterface;
10+
use PhpSpec\ObjectBehavior;
11+
12+
class FilterSpec extends ObjectBehavior
13+
{
14+
public function it_can_filter_a_tree_with_a_callback()
15+
{
16+
$tree = new ValueNode('root', 10);
17+
18+
$nodes = [];
19+
20+
foreach (range(1, 11) as $value) {
21+
$nodes[] = new ValueNode($value);
22+
}
23+
$tree->add(...$nodes);
24+
25+
$this
26+
->modify($tree)
27+
->count()
28+
->shouldReturn(6);
29+
}
30+
31+
public function it_is_initializable()
32+
{
33+
$this->shouldHaveType(Filter::class);
34+
}
35+
36+
public function let()
37+
{
38+
$this->beConstructedWith(
39+
static function (ValueNodeInterface $node) {
40+
return 0 === ($node->getValue() % 2);
41+
}
42+
);
43+
}
44+
}

src/Modifier/Filter.php

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace loophp\phptree\Modifier;
6+
7+
use loophp\phptree\Node\NodeInterface;
8+
9+
/**
10+
* Class Filter.
11+
*/
12+
class Filter implements ModifierInterface
13+
{
14+
/**
15+
* @var callable
16+
*/
17+
private $filter;
18+
19+
/**
20+
* Filter constructor.
21+
*
22+
* @param callable $filter
23+
*/
24+
public function __construct(callable $filter)
25+
{
26+
$this->filter = $filter;
27+
}
28+
29+
/**
30+
* {@inheritdoc}
31+
*/
32+
public function modify(NodeInterface $tree): NodeInterface
33+
{
34+
/** @var \loophp\phptree\Node\MerkleNode $item */
35+
foreach ($tree->all() as $item) {
36+
if (null === $parent = $item->getParent()) {
37+
continue;
38+
}
39+
40+
if (false === (bool) ($this->filter)($item)) {
41+
continue;
42+
}
43+
44+
$parent->remove($item);
45+
$this->modify($parent);
46+
}
47+
48+
return $tree;
49+
}
50+
}

0 commit comments

Comments
 (0)