DateRangeIterator::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 4
nc 8
nop 4
1
<?php
2
3
namespace itertools;
4
5
use DateInterval;
6
use DateTime;
7
use Iterator;
8
9
10
class DateRangeIterator implements Iterator
11
{
12
	const INCLUDE_BOTH = 0;
13
	const EXCLUDE_LEFT = 1;
14
	const EXCLUDE_RIGHT = 2;
15
16
	protected $startDate;
17
	protected $currentDate;
18
	protected $endDate;
19
	protected $index;
20
	protected $borderInclusion;
21
	protected $interval;
22
23
	public function __construct($startDate, $endDate, $interval, $borderInclusion = self::INCLUDE_BOTH)
24
	{
25
		$this->borderInclusion = $borderInclusion;
26
		$this->startDate = is_string($startDate) ? new DateTime($startDate) : $startDate;
27
		$clonedStart = clone $this->startDate;
28
		$this->endDate = is_string($endDate) ? $clonedStart->modify($endDate) : $endDate;
29
		$this->interval = is_string($interval) ? DateInterval::createFromDateString($interval) : $interval;
30
	}
31
32
	public function valid()
33
	{
34
		if(null === $this->currentDate) {
35
			return false;
36
		}
37
		if($this->currentDate < $this->endDate) {
38
			return true;
39
		}
40
		return $this->currentDate == $this->endDate && !($this->borderInclusion & self::EXCLUDE_RIGHT);
41
	}
42
43
	public function rewind()
44
	{
45
		$this->index = 0;
46
		$this->currentDate = clone $this->startDate;
47
		if($this->borderInclusion & self::EXCLUDE_LEFT) {
48
			$this->next();
49
		}
50
	}
51
52
	public function next()
53
	{
54
		$this->currentDate->add($this->interval);
55
		$this->index += 1;
56
	}
57
58
	public function key()
59
	{
60
		return $this->index;
61
	}
62
63
	public function current()
64
	{
65
		return clone $this->currentDate;
66
	}
67
}
68
69