Passed
Push — master ( 37710c...345016 )
by Bobby
09:30
created

Distance::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
namespace Ballen\Distical\Entities;
3
4
/**
5
 * Distical
6
 *
7
 * Distical is a simple distance calculator library for PHP 5.3+ which
8
 * amongst other things can calculate the distance between two or more lat/long
9
 * co-ordinates.
10
 *
11
 * @author Bobby Allen <[email protected]>
12
 * @license http://opensource.org/licenses/MIT
13
 * @link https://github.com/allebb/distical
14
 * @link http://bobbyallen.me
15
 *
16
 */
17
class Distance
18
{
19
20
    /**
21
     * Converstion from Kilomters to Miles.
22
     */
23
    const KILOMETERS_IN_MILES = 0.621371192;
24
25
    /**
26
     * Converstion from Kilomters to Naugtical miles.
27
     */
28
    const KILOMETERS_INL_NAUTICAL_MILES = 0.539956803;
29
30
    /**
31
     * The distance in kilometres
32
     * @var double|int
33
     */
34
    private $kilometres;
35
36
    /**
37
     * Class constructor
38
     * @param mixed $kilometres The distance in kilometres.
39
     */
40 22
    public function __construct($kilometres = 0)
41
    {
42 22
        $this->validateDistance($kilometres);
43 22
        $this->kilometres = $kilometres;
44 22
    }
45
46
    /**
47
     * Validates the distance constructor value.
48
     * @param mixed $distance
49
     * @throws \InvalidArgumentException
50
     * @return void
51
     */
52 22
    private function validateDistance($distance)
53
    {
54 22
        if (!is_numeric($distance)) {
55 1
            throw new \InvalidArgumentException('The distance value must be of a valid type.');
56
        }
57 22
        if (!$distance > 0) {
58 1
            throw new \InvalidArgumentException('The distance must be greater than zero!');
59
        }
60 22
    }
61
62
    /**
63
     * Distance as kilometres
64
     * @return double
65
     */
66 9
    public function asKilometres()
67
    {
68 9
        return $this->kilometres;
69
    }
70
71
    /**
72
     * Distance as miles
73
     * @return double
74
     */
75 5
    public function asMiles()
76
    {
77 5
        return $this->kilometres * self::KILOMETERS_IN_MILES;
78
    }
79
80
    /**
81
     * Distance as nautical miles
82
     * @return double
83
     */
84 4
    public function asNauticalMiles()
85
    {
86 4
        return $this->kilometres * self::KILOMETERS_INL_NAUTICAL_MILES;
87
    }
88
89
    /**
90
     * Default __toString() method, defaults to returning the distance as kilometres.
91
     * @return string
92
     */
93 4
    public function __toString()
94
    {
95 4
        return (string) $this->asKilometres();
96
    }
97
}
98