StaticPathfinder::from()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 17
rs 9.6111
cc 5
nc 5
nop 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Pathfinder;
4
5
final class StaticPathfinder implements Pathfinder
6
{
7
    private $index;
8
    private $network;
9
10
    private function __construct(ShortestPathForest $index, Network $network)
11
    {
12
        $this->index = $index;
13
        $this->network = $network;
14
    }
15
16
    public static function using(
17
        ShortestPathForest $index,
18
        Network $network
19
    ): Pathfinder {
20
        return new self($index, $network);
21
    }
22
23
    public function from(string $start): array
24
    {
25
        if (!$this->network->has($start)) {
26
            throw NonExistingStart::tried($start);
27
        }
28
29
        $paths = [];
30
        foreach ($this->network->all() as $goal) {
31
            if ($start !== $goal) {
32
                try {
33
                    $paths[$goal] = $this->between($start, $goal);
34
                } catch (NoPathAvailable $unreachableNode) {
35
                    // the node is not reachable: simply leave it out.
36
                }
37
            }
38
        }
39
        return $paths;
40
    }
41
42
    public function between(string $start, string $goal): array
43
    {
44
        $path = [$start];
45
        $node = $start;
46
        while ($node !== $goal) {
47
            $node = $this->index->nextStepOnTheRoadBetween($node, $goal);
48
            $path[] = $node;
49
        }
50
        return $path;
51
    }
52
}
53