forked from Respect/Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionIterator.php
More file actions
64 lines (49 loc) · 1.6 KB
/
CollectionIterator.php
File metadata and controls
64 lines (49 loc) · 1.6 KB
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
<?php
declare(strict_types=1);
namespace Respect\Data;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use Respect\Data\Collections\Collection;
use function array_filter;
use function is_array;
/** @extends RecursiveArrayIterator<array-key, Collection> */
final class CollectionIterator extends RecursiveArrayIterator
{
/** @var array<string, int> */
protected array $namesCounts = [];
/**
* @param Collection|array<Collection> $target
* @param array<string, int> $namesCounts
*/
public function __construct(Collection|array $target = [], array &$namesCounts = [])
{
$this->namesCounts = &$namesCounts;
$items = is_array($target) ? $target : [$target];
parent::__construct($items);
}
/** @return RecursiveIteratorIterator<CollectionIterator>&iterable<string, Collection> */
public static function recursive(Collection $target): RecursiveIteratorIterator
{
return new RecursiveIteratorIterator(new self($target), 1);
}
public function key(): string
{
$name = $this->current()->name ?? '';
if (isset($this->namesCounts[$name])) {
return $name . ++$this->namesCounts[$name];
}
$this->namesCounts[$name] = 1;
return $name;
}
public function hasChildren(): bool
{
return $this->current()->hasChildren;
}
public function getChildren(): RecursiveArrayIterator
{
return new static(
array_filter($this->current()->with, static fn(Collection $c): bool => $c->name !== null),
$this->namesCounts,
);
}
}