Sun::setSunrise()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 1
c 2
b 1
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Rawaby88\OpenWeatherMap\Services\Support;
4
5
use DateTime;
6
use LogicException;
7
8
/**
9
 * Class Sun.
10
 */
11
class Sun
12
{
13
    /**
14
     * @var DateTime The sunrise time.
15
     */
16
    public $sunrise;
17
18
    /**
19
     * @var DateTime The sunset time.
20
     */
21
    public $sunset;
22
23
    /**
24
     * @var int The timezone.
25
     */
26
    public $timezone;
27
28
    /**
29
     * Create a new sun object.
30
     *
31
     * @param int $sunrise The sunrise time.
32
     * @param int $sunset The sunset time.
33
     * @param int $timezone
34
     *
35
     * @internal
36
     */
37
    public function __construct(int $sunrise, int $sunset, int $timezone)
38
    {
39
        if ($sunset < $sunrise) {
40
            throw new LogicException('Sunset cannot be before sunrise!');
41
        }
42
43
        $this->timezone = $timezone;
44
        $this->setSunrise($sunrise);
45
        $this->setSunset($sunset);
46
    }
47
48
    /**
49
     * Set sunrise time.
50
     * @param int $sunrise
51
     */
52
    public function setSunrise(int $sunrise): void
53
    {
54
        $this->sunrise = DateTime::createFromFormat('U', $sunrise + $this->timezone);
55
    }
56
57
    /**
58
     * Set sunset time.
59
     * @param int $sunset
60
     */
61
    public function setSunset(int $sunset): void
62
    {
63
        $this->sunset = DateTime::createFromFormat('U', $sunset + $this->timezone);
64
    }
65
66
    /**
67
     * Encoding to json.
68
     * @return false|string
69
     */
70
    public function toJson()
71
    {
72
        return json_encode(
73
            [
74
                'sunrise'  => $this->sunrise,
75
                'sunset'   => $this->sunset,
76
                'timezone' => $this->timezone,
77
            ]
78
        );
79
    }
80
}
81