|
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
|
|
|
public function __construct(Direction $direction, $number) |
|
29
|
|
|
{ |
|
30
|
|
|
if (false === filter_var($number, FILTER_VALIDATE_INT)) { |
|
31
|
|
|
throw new \InvalidArgumentException('Integer required'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
if ($number <= 0) { |
|
35
|
|
|
throw new \OutOfBoundsException('Day of month less than 1'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$this->direction = $direction; |
|
39
|
|
|
$this->number = $number; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param string $date |
|
44
|
|
|
* @param Period $period |
|
45
|
|
|
* @return string |
|
46
|
|
|
*/ |
|
47
|
|
|
public function select($date, Period $period) |
|
48
|
|
|
{ |
|
49
|
|
|
$numberOfDays = min($this->number - 1, $period->getNumberOfDays()); |
|
50
|
|
|
$result = $this->getDateAfterNumberOfDays($period->getStartDate(), $numberOfDays); |
|
51
|
|
|
|
|
52
|
|
|
if ($this->direction->compare($date, $result) !== -1) { |
|
53
|
|
|
$this->direction->next($period); |
|
54
|
|
|
$numberOfDays = min($this->number - 1, $period->getNumberOfDays()); |
|
55
|
|
|
$result = $this->getDateAfterNumberOfDays($period->getStartDate(), $numberOfDays); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $result; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @param string $date |
|
63
|
|
|
* @param int $numberOfDays |
|
64
|
|
|
* @return string |
|
65
|
|
|
*/ |
|
66
|
|
|
private function getDateAfterNumberOfDays($date, $numberOfDays) |
|
67
|
|
|
{ |
|
68
|
|
|
$startDate = new \DateTime($date); |
|
69
|
|
|
$startDate->add(new \DateInterval(sprintf('P%dD', $numberOfDays))); |
|
70
|
|
|
|
|
71
|
|
|
return $startDate->format('Y-m-d'); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|