DomainLogic::euclideanDistance()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace JMGQ\AStar\Example\Graph;
4
5
use JMGQ\AStar\DomainLogicInterface;
6
7
/**
8
 * @implements DomainLogicInterface<Coordinate>
9
 */
10
class DomainLogic implements DomainLogicInterface
11
{
12 6
    public function __construct(private Graph $graph)
13
    {
14 6
    }
15
16
    /**
17
     * @param Coordinate $node
18
     * @return Coordinate[]
19
     */
20 3
    public function getAdjacentNodes(mixed $node): iterable
21
    {
22 3
        return $this->graph->getDirectSuccessors($node);
23
    }
24
25
    /**
26
     * @param Coordinate $node
27
     * @param Coordinate $adjacent
28
     * @return float|int
29
     */
30 4
    public function calculateRealCost(mixed $node, mixed $adjacent): float | int
31
    {
32 4
        if (!$this->graph->hasLink($node, $adjacent)) {
33 1
            throw new \DomainException('The provided nodes are not linked');
34
        }
35
36
        /**
37
         * @phpstan-ignore-next-line
38
         * @psalm-suppress PossiblyNullReference
39
         * getLink cannot be null, as we just checked that the link exists
40
         */
41 3
        return $this->graph->getLink($node, $adjacent)->getDistance();
42
    }
43
44
    /**
45
     * @param Coordinate $fromNode
46
     * @param Coordinate $toNode
47
     * @return float|int
48
     */
49 3
    public function calculateEstimatedCost(mixed $fromNode, mixed $toNode): float | int
50
    {
51 3
        return $this->euclideanDistance($fromNode, $toNode);
52
    }
53
54 3
    private function euclideanDistance(Coordinate $a, Coordinate $b): float
55
    {
56 3
        $xFactor = ($a->getX() - $b->getX()) ** 2;
57 3
        $yFactor = ($a->getY() - $b->getY()) ** 2;
58
59 3
        return sqrt($xFactor + $yFactor);
60
    }
61
}
62