Shake::getBlacklistedNodes()   B
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 25
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 11
cts 11
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 10
nc 2
nop 2
crap 4
1
<?php
2
3
namespace Vine\Commands;
4
5
use Vine\Node;
6
use Vine\NodeCollection;
7
8
class Shake
9
{
10
    /**
11
     * Shake node collection by a callback so only the filtered nodes are left as children with respect to their ancestor relations.
12
     * Shaking a collection retains the ancestors for each filtered node
13
     * Pruning a collection only keeps the filtered nodes and collapses the ancestor tree.
14
     *
15
     * @param Node $node
16
     * @param callable $callback
17
     * @param bool $prune -
18
     * @return Node
19
     * @internal param Node[] $nodes
20
     */
21 9 View Code Duplication
    public function __invoke(Node $node, Callable $callback, $prune = false): Node
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
22
    {
23 9
        $shakedNode = $node->isolatedCopy();
24 9
        $copiedNode = $node->copy();
25
26 9
        $shakedChildren = (new Slice())($copiedNode->children(), ...$this->getBlacklistedNodes($copiedNode, $callback));
27
28 9
        return $shakedNode->addChildren($shakedChildren);
29
    }
30
31
    /**
32
     * Blacklist of allowed nodes - we reverse the callback so we get the nodes that we do not want included
33
     * @param $copiedNode
34
     * @param callable $callback
35
     * @return array
36
     */
37 9
    private function getBlacklistedNodes(Node $copiedNode, Callable $callback): array
38
    {
39 9
        $flatten = (new Flatten())($copiedNode->children());
40
41 9
        $whitelistedNodes = new NodeCollection(...array_filter($flatten->all(),$callback));
42
43 9
        foreach($whitelistedNodes as $node)
44
        {
45 6
            $whitelistedNodes->merge($node->ancestors());
46
        }
47
48 9
        return array_filter($flatten->all(), function (Node $node) use ($whitelistedNodes)
49
        {
50
            // Todo we should make this check optimized for performance
51 9
            foreach($whitelistedNodes as $whitelistedNode)
52
            {
53 6
                if($node->equals($whitelistedNode))
54
                {
55 6
                    return false;
56
                }
57
            }
58
59 6
            return true;
60 9
        });
61
    }
62
}
63