SequencePrinter::getCoordinateAsString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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