Completed
Pull Request — master (#10)
by Yılmaz
02:30
created

GeoPoint::getPoint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Represents a latitude and longitude pair.
4
 * 
5
 * @author  M. Yilmaz SUSLU <[email protected]>
6
 * @license MIT
7
 *
8
 * @since   Sep 2016
9
 */
10
namespace DDD\Embeddable;
11
12
use Doctrine\ORM\Mapping as ORM;
13
use JsonSerializable;
14
15
/**
16
 * @ORM\Embeddable
17
 */
18
class GeoPoint implements JsonSerializable
19
{
20
    /**
21
     * geo point value, stored as associative array
22
     *
23
     * @ORM\Column(type="array", nullable=true)
24
     * 
25
     * @var array
26
     */
27
    private $point;
28
29
    /**
30
     * Constructor
31
     *
32
     * @param float $lat Latitude
33
     * @param float $lng Longitude
34
     */
35 5
    public function __construct($lat = null, $lng = null)
36
    {
37 5
        if ($lat && $lng) {
38 4
            if ($lat < -90.0 || $lat > 90.0 || $lng < -180.0 || $lng > 180.0) {
39 1
                throw new \InvalidArgumentException('Given latitude longitude pair is invalid.');
40
            }
41
42 3
            $this->point = [
43 3
                'lat' => (float) $lat,
44 3
                'lng' => (float) $lng,
45
            ];
46 3
        }
47 4
    }
48
49
    /**
50
     * return elasticsearch-friendly geo point format.
51
     *
52
     * Beware: Elastic uses lat/lon as keys. Google uses lat/lng.
53
     * 
54
     * @return array
55
     */
56 3
    public function toElastic()
57
    {
58 3
        if (empty($this->point)) {
59 1
            return [];
60
        }
61
62
        return [
63 2
            'lat' => $this->point['lat'],
64 2
            'lon' => $this->point['lng'],
65 2
        ];
66
    }
67
68
    /**
69
     * Array representation of the geo point
70
     * 
71
     * @return array
72
     */
73 4
    public function toArray()
74
    {
75 4
        return $this->point ?: [];
76
    }
77
78
    /**
79
     * Implement json serializable interface.
80
     * 
81
     * @return array
82
     */
83 1
    public function jsonSerialize()
84
    {
85 1
        return $this->toArray();
86
    }
87
88
    /**
89
     * String representation of the point, lat lng order, separated by a space.
90
     * 
91
     * @return string
92
     */
93 1
    public function __toString()
94
    {
95 1
        if (empty($this->point)) {
96 1
            return '';
97
        }
98
99 1
        return $this->point['lat'].' '.$this->point['lng'];
100
    }
101
}
102