graph-tools-php
49 строк · 1.6 Кб
1<?php
2
3namespace Smoren\GraphTools\Helpers;
4
5use Generator;
6use Smoren\GraphTools\Models\Interfaces\VertexInterface;
7use Smoren\GraphTools\Structs\Interfaces\TraverseContextInterface;
8
9/**
10* Helper for getting traversing results
11* @author Smoren <ofigate@gmail.com>
12*/
13class 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*/
21public static function getBranches(Generator $contexts, ?callable $callback = null): array
22{
23$branchMap = [];
24foreach($contexts as $context) {
25if(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
34if(!isset($branchMap[$branchIndex])) {
35if(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
47return $branchMap;
48}
49}
50