TraverseHelper::getBranches()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 7
nop 2
dl 0
loc 27
rs 9.3888
c 0
b 0
f 0
1
<?php
2
3
namespace Smoren\GraphTools\Helpers;
4
5
use Generator;
6
use Smoren\GraphTools\Models\Interfaces\VertexInterface;
7
use Smoren\GraphTools\Structs\Interfaces\TraverseContextInterface;
8
9
/**
10
 * Helper for getting traversing results
11
 * @author Smoren <[email protected]>
12
 */
13
class TraverseHelper
14
{
15
    /**
16
     * Returns branches of traversing (every branch as array of Vertex objects)
17
     * @param Generator<TraverseContextInterface> $contexts traverse contexts' iterator
18
     * @param callable|null $callback action to do for each context
19
     * @return array<int, array<VertexInterface>> branch list
20
     */
21
    public static function getBranches(Generator $contexts, ?callable $callback = null): array
22
    {
23
        $branchMap = [];
24
        foreach($contexts as $context) {
25
            if(is_callable($callback)) {
26
                $callback($context, $contexts);
27
            }
28
29
            $branchContext = $context->getBranchContext();
30
            $branchIndex = $branchContext->getIndex();
31
            $parentBranchIndex = $context->getBranchContext()->getParentIndex();
32
            $vertex = $context->getVertex();
33
34
            if(!isset($branchMap[$branchIndex])) {
35
                if(isset($branchMap[$parentBranchIndex])) {
36
                    $parentBranch = $branchMap[$parentBranchIndex];
37
                    $key = array_search($branchContext->getStart(), $parentBranch);
38
                    $branchMap[$branchIndex] = array_slice($parentBranch, 0, $key+1);
39
                } else {
40
                    $branchMap[$branchIndex] = [];
41
                }
42
            }
43
44
            $branchMap[$branchIndex][] = $vertex;
45
        }
46
47
        return $branchMap;
48
    }
49
}
50