scratch – Blame information for rev
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
87 | office | 1 | <?php |
2 | |||
3 | /* |
||
4 | * This file is part of Fusonic-linq. |
||
5 | * https://github.com/fusonic/fusonic-linq |
||
6 | * |
||
7 | * (c) Fusonic GmbH |
||
8 | * |
||
9 | * For the full copyright and license information, please view the LICENSE |
||
10 | * file that was distributed with this source code. |
||
11 | */ |
||
12 | |||
13 | namespace Fusonic\Linq\Iterator; |
||
14 | |||
15 | use Iterator; |
||
16 | use ArrayIterator; |
||
17 | use Fusonic\Linq\GroupedLinq; |
||
18 | |||
19 | class GroupIterator implements Iterator |
||
20 | { |
||
21 | private $iterator; |
||
22 | private $grouped; |
||
23 | private $keySelector; |
||
24 | |||
25 | public function __construct($iterator, $keySelector) |
||
26 | { |
||
27 | $this->iterator = $iterator; |
||
28 | $this->keySelector = $keySelector; |
||
29 | } |
||
30 | |||
31 | public function current() |
||
32 | { |
||
33 | $current = $this->grouped->current(); |
||
34 | return new GroupedLinq($current['key'], new \ArrayIterator($current['values'])); |
||
35 | } |
||
36 | |||
37 | public function next() |
||
38 | { |
||
39 | $this->grouped->next(); |
||
40 | } |
||
41 | |||
42 | public function key() |
||
43 | { |
||
44 | return $this->grouped->key(); |
||
45 | } |
||
46 | |||
47 | public function valid() |
||
48 | { |
||
49 | return $this->grouped->valid(); |
||
50 | } |
||
51 | |||
52 | public function rewind() |
||
53 | { |
||
54 | if ($this->grouped === null) { |
||
55 | $this->doGroup(); |
||
56 | } |
||
57 | |||
58 | $this->grouped->rewind(); |
||
59 | } |
||
60 | |||
61 | private function doGroup() |
||
62 | { |
||
63 | $keySelector = $this->keySelector; |
||
64 | $this->grouped = new \ArrayIterator(array()); |
||
65 | foreach ($this->iterator as $value) { |
||
66 | $key = $keySelector($value); |
||
67 | if (!isset($this->grouped[$key])) { |
||
68 | $this->grouped[$key] = array('key' => $key, 'values'=> array()); |
||
69 | } |
||
70 | |||
71 | $this->grouped[$key]['values'][] = $value; |
||
72 | } |
||
73 | } |
||
74 | } |