1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace COG\ChronoShifter\Selector; |
4
|
|
|
|
5
|
|
|
use COG\ChronoShifter\Direction\Direction; |
6
|
|
|
use COG\ChronoShifter\Evaluator\Evaluator; |
7
|
|
|
use COG\ChronoShifter\Period\Period; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @author Kristjan Siimson <[email protected]> |
11
|
|
|
* @package Selector\Domain |
12
|
|
|
*/ |
13
|
|
View Code Duplication |
class LastOf implements Selector |
|
|
|
|
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var Direction |
17
|
|
|
*/ |
18
|
|
|
private $direction; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var Evaluator |
22
|
|
|
*/ |
23
|
|
|
private $evaluator; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param Direction $direction |
27
|
|
|
* @param Evaluator $evaluator |
28
|
|
|
*/ |
29
|
22 |
|
public function __construct(Direction $direction, Evaluator $evaluator) |
30
|
|
|
{ |
31
|
22 |
|
$this->direction = $direction; |
32
|
22 |
|
$this->evaluator = $evaluator; |
33
|
22 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param string $date |
37
|
|
|
* @param Period $period |
38
|
|
|
* @return string |
39
|
|
|
*/ |
40
|
22 |
|
public function select($date, Period $period) |
41
|
|
|
{ |
42
|
22 |
|
$match = $this->getLastInPeriod( |
43
|
22 |
|
new \DateTime($period->getStartDate()), |
44
|
22 |
|
new \DateTime($period->getEndDate()) |
45
|
22 |
|
); |
46
|
|
|
|
47
|
22 |
|
if ($this->direction->compare($date, $match) !== -1) { |
48
|
15 |
|
$this->direction->next($period); |
49
|
15 |
|
$match = $this->getLastInPeriod( |
50
|
15 |
|
new \DateTime($period->getStartDate()), |
51
|
15 |
|
new \DateTime($period->getEndDate()) |
52
|
15 |
|
); |
53
|
15 |
|
} |
54
|
|
|
|
55
|
22 |
|
return $match; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param \DateTime $startDate |
60
|
|
|
* @param \DateTime $endDate |
61
|
|
|
* @return null|string |
62
|
|
|
* @throws \LogicException |
63
|
|
|
*/ |
64
|
22 |
|
private function getLastInPeriod(\DateTime $startDate, \DateTime $endDate) |
65
|
|
|
{ |
66
|
22 |
|
$match = null; |
67
|
|
|
|
68
|
22 |
|
for ($i = clone $endDate; $i > $startDate; $i->sub(new \DateInterval('P1D'))) { |
69
|
22 |
|
if ($this->evaluator->is($i->format('Y-m-d'))) { |
70
|
22 |
|
$match = $i->format('Y-m-d'); |
71
|
22 |
|
break; |
72
|
|
|
} |
73
|
17 |
|
} |
74
|
|
|
|
75
|
22 |
|
if ($match === null) { |
76
|
|
|
throw new \LogicException('No match in period'); |
77
|
|
|
} |
78
|
|
|
|
79
|
22 |
|
return $match; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.