Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
8 / 8 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
TraverseUtility | |
100.00% |
8 / 8 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
toIterator | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
toArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace PeServer\Core\Collection; |
6 | |
7 | use ArrayIterator; |
8 | use Iterator; |
9 | use IteratorAggregate; |
10 | use IteratorIterator; |
11 | use Traversable; |
12 | |
13 | /** |
14 | * `Traversable` に対する共通処理。 |
15 | */ |
16 | abstract class TraverseUtility |
17 | { |
18 | #region function |
19 | |
20 | /** |
21 | * イテレータに変換。 |
22 | * |
23 | * @template TKey of array-key |
24 | * @template TValue |
25 | * @param Traversable|array<mixed>|callable $sequence |
26 | * @phpstan-param Traversable<TKey,TValue>|array<TKey,TValue>|callable():\Generator<TKey,TValue> $sequence |
27 | * @return Iterator |
28 | * @phpstan-return Iterator<TKey,TValue> |
29 | */ |
30 | public static function toIterator(Traversable|array|callable $sequence): Iterator |
31 | { |
32 | if ($sequence instanceof IteratorAggregate) { |
33 | return new IteratorIterator($sequence); |
34 | } |
35 | if ($sequence instanceof Iterator) { |
36 | return $sequence; |
37 | } |
38 | if (is_callable($sequence)) { |
39 | return new GeneratorIterator($sequence); |
40 | } |
41 | |
42 | assert(is_array($sequence)); |
43 | return new ArrayIterator($sequence); |
44 | } |
45 | |
46 | /** |
47 | * `Traversable` を配列に変換。 |
48 | * |
49 | * @template TKey of array-key |
50 | * @template TValue |
51 | * @param Traversable $traverse |
52 | * @phpstan-param Traversable<TKey,TValue> $traverse |
53 | * @param bool $preserveKeys |
54 | * @return array |
55 | * @phpstan-return array<TKey,TValue> |
56 | */ |
57 | public static function toArray(Traversable $traverse, bool $preserveKeys): array |
58 | { |
59 | return iterator_to_array($traverse, $preserveKeys); |
60 | } |
61 | |
62 | #endregion |
63 | } |