SequencePrinter   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 22
dl 0
loc 58
ccs 27
cts 27
cp 1
rs 10
c 1
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A getCoordinateAsString() 0 3 1
A printSequence() 0 16 3
A getTotalDistance() 0 25 4
1
<?php
2
3
namespace JMGQ\AStar\Example\Graph;
4
5
class SequencePrinter
6
{
7
    /**
8
     * @param Graph $graph
9
     * @param iterable<Coordinate> $sequence
10
     */
11 4
    public function __construct(private Graph $graph, private iterable $sequence)
12
    {
13 4
    }
14
15 4
    public function printSequence(): void
16
    {
17 4
        $coordinatesAsString = [];
18
19 4
        foreach ($this->sequence as $coordinate) {
20 3
            $coordinatesAsString[] = $this->getCoordinateAsString($coordinate);
21
        }
22
23 4
        $cost = $this->getTotalDistance();
24
25 3
        if (!empty($coordinatesAsString)) {
26 2
            echo implode(' => ', $coordinatesAsString);
27 2
            echo "\n";
28
        }
29
30 3
        echo "Total cost: $cost";
31 3
    }
32
33 3
    private function getCoordinateAsString(Coordinate $coordinate): string
34
    {
35 3
        return "({$coordinate->getX()}, {$coordinate->getY()})";
36
    }
37
38 4
    private function getTotalDistance(): float | int
39
    {
40
        /** @var Coordinate[] $sequence */
41 4
        $sequence = (array) $this->sequence;
42
43 4
        if (count($sequence) < 2) {
44 2
            return 0;
45
        }
46
47 2
        $totalDistance = 0;
48
49 2
        $previousNode = array_shift($sequence);
50 2
        foreach ($sequence as $node) {
51 2
            $link = $this->graph->getLink($previousNode, $node);
52
53 2
            if (!$link) {
54 1
                throw new \RuntimeException('Some of the nodes in the provided sequence are not connected');
55
            }
56
57 2
            $totalDistance += $link->getDistance();
58
59 2
            $previousNode = $node;
60
        }
61
62 1
        return $totalDistance;
63
    }
64
}
65