|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Gielfeldt\Iterators; |
|
4
|
|
|
|
|
5
|
|
|
class RecursiveSortIterator extends SortIterator implements \RecursiveIterator |
|
6
|
|
|
{ |
|
7
|
|
|
protected $children = []; |
|
8
|
|
|
|
|
9
|
3 |
|
public function __construct(\Traversable $iterator, int $direction = self::SORT_ASC, int $flags = 0, callable $callback = self::SORT_CURRENT) |
|
10
|
|
|
{ |
|
11
|
3 |
|
$iterator = $iterator instanceof \IteratorAggregate ? $iterator->getIterator() : $iterator; |
|
12
|
3 |
|
if (!$iterator instanceof \RecursiveIterator) { |
|
13
|
1 |
|
throw new \InvalidArgumentException('An instance of RecursiveIterator or IteratorAggregate creating it is required'); |
|
14
|
|
|
} |
|
15
|
2 |
|
parent::__construct($iterator, $direction, $flags, $callback); |
|
16
|
2 |
|
} |
|
17
|
|
|
|
|
18
|
2 |
|
public function getSortedIterator($iterator) |
|
19
|
|
|
{ |
|
20
|
2 |
|
$sortedIterator = new \RecursiveArrayIterator(); |
|
21
|
2 |
|
$sorted = []; |
|
22
|
2 |
|
foreach ($iterator as $key => $value) { |
|
23
|
2 |
|
if ($iterator->hasChildren()) { |
|
24
|
2 |
|
$this->children[$key] = $iterator->getChildren(); |
|
25
|
|
|
} |
|
26
|
2 |
|
$sorted[] = $this->generateElement($key, $value, $iterator); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
2 |
|
usort($sorted, $this->realCallback); |
|
30
|
|
|
|
|
31
|
2 |
|
foreach ($sorted as $data) { |
|
32
|
2 |
|
$sortedIterator->append($data); |
|
33
|
|
|
} |
|
34
|
2 |
|
return $sortedIterator; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
2 |
|
public function hasChildren() |
|
38
|
|
|
{ |
|
39
|
2 |
|
return isset($this->children[$this->key()]); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
2 |
|
public function getChildren() |
|
43
|
|
|
{ |
|
44
|
2 |
|
return new self($this->children[$this->key()], $this->direction, $this->flags, $this->callback); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|