1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace COG\ChronoShifter\Selector; |
4
|
|
|
|
5
|
|
|
use COG\ChronoShifter\Direction\Direction; |
6
|
|
|
use COG\ChronoShifter\Period\Period; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @author Kristjan Siimson <[email protected]> |
10
|
|
|
* @package Selector\Domain |
11
|
|
|
*/ |
12
|
|
|
class Specific implements Selector |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var Direction |
16
|
|
|
*/ |
17
|
|
|
private $direction; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var int |
21
|
|
|
*/ |
22
|
|
|
private $number; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param Direction $direction |
26
|
|
|
* @param int $number |
27
|
|
|
*/ |
28
|
45 |
|
public function __construct(Direction $direction, $number) |
29
|
|
|
{ |
30
|
45 |
|
if (false === filter_var($number, FILTER_VALIDATE_INT)) { |
31
|
1 |
|
throw new \InvalidArgumentException('Integer required'); |
32
|
|
|
} |
33
|
|
|
|
34
|
44 |
|
if ($number <= 0) { |
35
|
1 |
|
throw new \OutOfBoundsException('Day of month less than 1'); |
36
|
|
|
} |
37
|
|
|
|
38
|
43 |
|
$this->direction = $direction; |
39
|
43 |
|
$this->number = $number; |
40
|
43 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $date |
44
|
|
|
* @param Period $period |
45
|
|
|
* @return string |
46
|
|
|
*/ |
47
|
43 |
|
public function select($date, Period $period) |
48
|
|
|
{ |
49
|
43 |
|
$numberOfDays = min($this->number - 1, $period->getNumberOfDays()); |
50
|
43 |
|
$result = $this->getDateAfterNumberOfDays($period->getStartDate(), $numberOfDays); |
51
|
|
|
|
52
|
43 |
|
if ($this->direction->compare($date, $result) !== -1) { |
53
|
28 |
|
$this->direction->next($period); |
54
|
28 |
|
$numberOfDays = min($this->number - 1, $period->getNumberOfDays()); |
55
|
28 |
|
$result = $this->getDateAfterNumberOfDays($period->getStartDate(), $numberOfDays); |
56
|
28 |
|
} |
57
|
|
|
|
58
|
43 |
|
return $result; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $date |
63
|
|
|
* @param int $numberOfDays |
64
|
|
|
* @return string |
65
|
|
|
*/ |
66
|
43 |
|
private function getDateAfterNumberOfDays($date, $numberOfDays) |
67
|
|
|
{ |
68
|
43 |
|
$startDate = new \DateTime($date); |
69
|
43 |
|
$startDate->add(new \DateInterval(sprintf('P%dD', $numberOfDays))); |
70
|
|
|
|
71
|
43 |
|
return $startDate->format('Y-m-d'); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|