Completed
Push — master ( 157822...4c034e )
by Alexander
01:43
created

Producer::getBearingDate()   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
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace GetSky\AIRAC;
3
4
/**
5
 * Class Producer
6
 * @package GetSky\AIRAC
7
 */
8
class Producer
9
{
10
    /**
11
     * @var \DateTime
12
     */
13
    private $bearing;
14
15
    /**
16
     * @param \DateTime|null $bearing
17
     */
18 20
    public function __construct(\DateTime $bearing = null)
19
    {
20 20
         $this->bearing = $bearing ? $bearing : new \DateTime('2016-01-07');
21 20
    }
22
23
    /**
24
     * @return \DateTime
25
     */
26 2
    public function getBearingDate()
27
    {
28 2
        return $this->bearing;
29
    }
30
31
    /**
32
     * Get next AIRAC date.
33
     *
34
     * @param \DateTime $date
35
     *
36
     * @return Airac
37
     */
38 6
    public function next(\DateTime $date)
39
    {
40 6
        return $this->circle($date, 1);
41
    }
42
43
    /**
44
     * Get current AIRAC date.
45
     *
46
     * @param \DateTime $date
47
     *
48
     * @return Airac
49
     */
50 6
    public function now(\DateTime $date)
51
    {
52 6
        return $this->circle($date, 0);
53
    }
54
55
    /**
56
     * Get last AIRAC date.
57
     *
58
     * @param \DateTime $date
59
     *
60
     * @return Airac
61
     */
62 6
    public function last(\DateTime $date)
63
    {
64 6
        return $this->circle($date, -1);
65
    }
66
67
    /**
68
     * Generator AIRAC dates.
69
     *
70
     * @param \DateTime $date
71
     * @param $step
72
     *
73
     * @return Airac
74
     */
75 18
    private function circle(\DateTime $date, $step)
76
    {
77 18
        $positive = ($date >= $this->bearing) ? 1 : -1;
78 18
        $days = $date->diff($this->bearing)->days;
79 18
        $countCircle = $positive * floor($days / 28) + $step - (($positive < 0 && $days % 28 != 0) ? 1 : 0);
80 18
        $dateStart = clone $this->bearing;
81 18
        $dateStart->modify(($countCircle * 28) . ' day');
82 18
        $dateEnd = clone $dateStart;
83 18
        $dateEnd->modify('28 day');
84
        
85 18
        return new Airac($dateStart, $dateEnd, $this->calcNumber($dateStart));
86
    }
87
88
    /**
89
     *Calculated number of AIRAC.
90
     *
91
     * @param \DateTime $date
92
     *
93
     * @return string
94
     */
95 18
    private function calcNumber(\DateTime $date)
96
    {
97 18
        $year = \DateTime::createFromFormat('!Y', $date->format('Y'));
98 18
        $number = 1 + floor($year->diff($date)->days / 28);
99
        
100 18
        return $year->format('y') . sprintf("%02d", $number);
101
    }
102
}
103