-
Notifications
You must be signed in to change notification settings - Fork 2
/
Iterator.php
107 lines (90 loc) · 2.08 KB
/
Iterator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace DesignPatterns\Behavioral;
/**
* Concrete Iterator implements traversal algorithm
* \Iterator is built-in PHP interface
*/
class ReverseIterator implements \Iterator
{
/**
* Collection instance
* @var SimpleCollection
*/
private $collection;
/**
* @var int Stores the current traversal position
*/
private $position = 0;
public function __construct(SimpleCollection $collection)
{
$this->collection = $collection;
}
/**
* Rewind the Iterator to the first element
*/
public function rewind()
{
$this->position = count($this->collection->getItems()) - 1;
}
/**
* Return the current element
*/
public function current()
{
return $this->collection->getItems()[$this->position];
}
/**
* Return the key of the current element
*/
public function key()
{
return $this->position;
}
/**
* Move forward to next element
*/
public function next()
{
$this->position = $this->position - 1;
}
/**
* Checks if current position is valid
*/
public function valid()
{
return isset($this->collection->getItems()[$this->position]);
}
}
/**
* Concrete Collection provides one or several methods for working with collection
* and also implements a built-in \IteratorAggregate interface which guarantee what we can fetch 'right' iterator
*/
class SimpleCollection implements \IteratorAggregate
{
private $items = [];
public function addItem($item)
{
$this->items[] = $item;
return $this;
}
public function getItems()
{
return $this->items;
}
public function getIterator(): \Iterator
{
return new ReverseIterator($this);
}
}
# Client code example
$collection = (new SimpleCollection())->addItem('1st item')
->addItem('2nd item')
->addItem('3rd item');
// Go through collection in reverse order
foreach ($collection->getIterator() as $item) {
echo $item . PHP_EOL;
}
/* Output:
3rd item
2nd item
1st item */