Completed
Push — master ( 4a2f3f...6ed42c )
by Bryan
18:05 queued 57s
created

Unit::getFormatted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
namespace Bhhaskin\WeatherBee\Util;
3
4
/**
5
*   Class for handling values with units
6
*/
7
class Unit
8
{
9
    /**
10
    * The value
11
    * @var float
12
    * @internal
13
    */
14
    private $value;
15
16
    /**
17
    * The value's unit
18
    * @var string
19
    * @internal
20
    */
21
    private $unit;
22
23
    /**
24
    * The value's description
25
    * @var string
26
    * @internal
27
    */
28
    private $description;
29
30
    /**
31
    * Create a new unit object
32
    * @param float  $value       The value
33
    * @param string $unit        The value's unit
34
    * @param string $description The value's description
35
    */
36 1
    public function __construct(float $value = 0.0, string $unit = null, string $description = null)
37
    {
38 1
        $this->value = $value;
39 1
        $this->unit = $unit;
40 1
        $this->description = $description;
41 1
    }
42
43
    /**
44
    * Get the value as formatted string with unit.
45
    * Unit will not be included if it is empty
46
    * @return string The value formatted string with unit.
47
    */
48 1
    public function __toString(): string
49
    {
50 1
        return $this->getFormatted();
51
    }
52
53
    /**
54
    * Get the value's unit.
55
    * This also converts 'celsius' to 'C' and 'fahrenheit' to 'F'.
56
    * @return string The value's unit.
57
    */
58 3
    public function getUnit(): ?string
59
    {
60 3
        if ($this->unit == 'celsius' || $this->unit == 'metric') {
61 1
            return "C";
62 2
        } elseif ($this->unit == 'fahrenheit') {
63 1
            return 'F';
64
        } else {
65 1
            return $this->unit;
66
        }
67
    }
68
69
    /**
70
    * Get the value.
71
    * @return float The value
72
    */
73 1
    public function getValue(): float
74
    {
75 1
        return $this->value;
76
    }
77
78
    /**
79
    * Get the value's description.
80
    * @return string Value's description.
81
    */
82 1
    public function getDescription(): ?string
83
    {
84 1
        return $this->description;
85
    }
86
87
    /**
88
    * Get the value as a formatted string with unit.
89
    * @return string The value as formatted string with unit.
90
    */
91 2
    public function getFormatted(): string
92
    {
93 2
        if (!empty($this->getUnit())) {
94 1
            return (string)$this->getValue() . " " . $this->getUnit();
95
        } else {
96 1
            return (string)$this->getValue();
97
        }
98
    }
99
}
100