Passed
Pull Request — master (#34)
by Benjamin
26:50 queued 11:50
created

Algorithm::getDistanceBetween()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Kmeans\Gps;
4
5
use Kmeans\Algorithm as BaseAlgorithm;
6
use Kmeans\Interfaces\PointCollectionInterface;
7
use Kmeans\Interfaces\PointInterface;
8
use Kmeans\Math;
9
10
class Algorithm extends BaseAlgorithm
11
{
12
    public function getDistanceBetween(PointInterface $pointA, PointInterface $pointB): float
13
    {
14
        if (! $pointA instanceof Point || ! $pointB instanceof Point) {
15
            throw new \InvalidArgumentException(
16
                "GPS algorithm can only calculate distance from GPS locations"
17
            );
18
        }
19
20
        return Math::haversine($pointA->getCoordinates(), $pointB->getCoordinates());
21
    }
22
23
    public function findCentroid(PointCollectionInterface $points): PointInterface
24
    {
25
        if (! $points->getSpace() instanceof Space) {
26
            throw new \InvalidArgumentException(
27
                "Point collection should consist of GPS coordinates"
28
            );
29
        }
30
31
        /** @var array<Point> $pointsArray */
32
        $pointsArray = iterator_to_array($points);
33
34
        return $points->getSpace()->makePoint(Math::gpsCentroid(
35
            array_map(fn (Point $point) => $point->getCoordinates(), $pointsArray)
36
        ));
37
    }
38
}
39