|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of php-fast-forward/iterators. |
| 7 | + * |
| 8 | + * This source file is subject to the license that is bundled |
| 9 | + * with this source code in the file LICENSE. |
| 10 | + * |
| 11 | + * @link https://github.com/php-fast-forward/iterators |
| 12 | + * @copyright Copyright (c) 2025 Felipe Sayão Lobato Abreu <[email protected]> |
| 13 | + * @license https://opensource.org/licenses/MIT MIT License |
| 14 | + */ |
| 15 | + |
| 16 | +use FastForward\Iterator\ClosureFactoryIteratorAggregate; |
| 17 | + |
| 18 | +use function FastForward\Iterator\debugIterable; |
| 19 | + |
| 20 | +require_once dirname(__DIR__) . '/vendor/autoload.php'; |
| 21 | + |
| 22 | +$len = 5; |
| 23 | + |
| 24 | +/** |
| 25 | + * Generator function to produce values dynamically. |
| 26 | + * |
| 27 | + * @param int $len the number of values to generate |
| 28 | + * |
| 29 | + * @return Generator<int, string> a generator yielding formatted strings |
| 30 | + */ |
| 31 | +$generatorFactory = static function (int $len = 10) { |
| 32 | + for ($i = 0; $i < $len; ++$i) { |
| 33 | + yield 'Value: ' . ($i + $len); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * Array-based factory to showcase alternative iteration strategy. |
| 39 | + * |
| 40 | + * @param int $len the number of values to include |
| 41 | + * |
| 42 | + * @return ArrayIterator<int, string> an ArrayIterator wrapping a static array |
| 43 | + */ |
| 44 | +$arrayFactory = static fn (int $len = 10) => new ArrayIterator(array_map(static fn ($i) => 'Value: ' . ($i + $len), range(0, $len - 1))); |
| 45 | + |
| 46 | +// Using ClosureFactoryIteratorAggregate with a Generator function |
| 47 | +$generatorIterator = new ClosureFactoryIteratorAggregate(static fn () => $generatorFactory($len)); |
| 48 | +// or |
| 49 | +// $generatorIterator = new ClosureFactoryIteratorAggregate($generatorFactory); |
| 50 | + |
| 51 | +// Using ClosureFactoryIteratorAggregate with an ArrayIterator |
| 52 | +$arrayIterator = new ClosureFactoryIteratorAggregate(static fn () => $arrayFactory($len)); |
| 53 | + |
| 54 | +debugIterable( |
| 55 | + $generatorIterator, |
| 56 | + 'ClosureFactoryIteratorAggregate :: Generator Strategy :: First Iteration', |
| 57 | +); |
| 58 | +debugIterable( |
| 59 | + $generatorIterator, |
| 60 | + 'ClosureFactoryIteratorAggregate :: Generator Strategy :: Second Iteration', |
| 61 | +); |
| 62 | + |
| 63 | +debugIterable( |
| 64 | + $arrayIterator, |
| 65 | + 'ClosureFactoryIteratorAggregate :: ArrayIterator Strategy :: First Iteration', |
| 66 | +); |
| 67 | +debugIterable( |
| 68 | + $arrayIterator, |
| 69 | + 'ClosureFactoryIteratorAggregate :: ArrayIterator Strategy :: Second Iteration', |
| 70 | +); |
0 commit comments