PointToLineDistance   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 53
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getDistance() 0 30 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Location\Utility;
6
7
use Location\Coordinate;
8
use Location\Distance\DistanceInterface;
9
use Location\Line;
10
11
/**
12
 * Calculate the distance between a Line and a Point.
13
 *
14
 * @author Marcus Jaschen <[email protected]>
15
 */
16
class PointToLineDistance
17
{
18
    /**
19
     * @var DistanceInterface
20
     */
21
    private $distanceCalculator;
22
23
    /**
24
     * PointToLineDistance constructor.
25
     * @param DistanceInterface $distanceCalculator
26
     */
27
    public function __construct(DistanceInterface $distanceCalculator)
28
    {
29
        $this->distanceCalculator = $distanceCalculator;
30
    }
31
32
    /**
33
     * @param Coordinate $point
34
     * @param Line $line
35
     *
36
     * @return float
37
     */
38
    public function getDistance(Coordinate $point, Line $line): float
39
    {
40
        if ($line->getPoint1()->hasSameLocation($line->getPoint2())) {
41
            return $this->distanceCalculator->getDistance($point, $line->getPoint1());
42
        }
43
44
        $pLat = deg2rad($point->getLat());
45
        $pLng = deg2rad($point->getLng());
46
47
        $l1Lat = deg2rad($line->getPoint1()->getLat());
48
        $l1Lng = deg2rad($line->getPoint1()->getLng());
49
        $l2Lat = deg2rad($line->getPoint2()->getLat());
50
        $l2Lng = deg2rad($line->getPoint2()->getLng());
51
52
        $deltal2l1Lat = $l2Lat - $l1Lat;
53
        $deltal2l1Lng = $l2Lng - $l1Lng;
54
55
        $u = (($pLat - $l1Lat) * $deltal2l1Lat + ($pLng - $l1Lng) * $deltal2l1Lng) /
56
            ($deltal2l1Lat ** 2 + $deltal2l1Lng ** 2);
57
58
        if ($u <= 0) {
59
            return $this->distanceCalculator->getDistance($point, $line->getPoint1());
60
        }
61
62
        if ($u >= 1) {
63
            return $this->distanceCalculator->getDistance($point, $line->getPoint2());
64
        }
65
66
        return (new PerpendicularDistance())->getPerpendicularDistance($point, $line);
67
    }
68
}
69