Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
2 / 2 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| ClosureIteratorIterator | |
100.00% |
2 / 2 |
|
100.00% |
2 / 2 |
2 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| current | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 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 | * @copyright Copyright (c) 2025-2026 Felipe Sayão Lobato Abreu <github@mentordosnerds.com> |
| 12 | * @license https://opensource.org/licenses/MIT MIT License |
| 13 | * |
| 14 | * @see https://github.com/php-fast-forward/iterators |
| 15 | * @see https://github.com/php-fast-forward |
| 16 | * @see https://datatracker.ietf.org/doc/html/rfc2119 |
| 17 | */ |
| 18 | |
| 19 | namespace FastForward\Iterator; |
| 20 | |
| 21 | use Closure; |
| 22 | |
| 23 | /** |
| 24 | * An extended IteratorIterator that applies a closure transformation |
| 25 | * to each element during iteration. |
| 26 | * |
| 27 | * This class allows applying a transformation function dynamically |
| 28 | * while iterating over an existing Traversable. |
| 29 | * |
| 30 | * ## Usage Example: |
| 31 | * |
| 32 | * @example |
| 33 | * ```php |
| 34 | * use FastForward\Iterator\ClosureIteratorIterator; |
| 35 | * use ArrayIterator; |
| 36 | * |
| 37 | * $array = [1, 2, 3, 4, 5]; |
| 38 | * |
| 39 | * $iterator = new ClosureIteratorIterator( |
| 40 | * new ArrayIterator($array), |
| 41 | * fn ($value) => $value * 2 |
| 42 | * ); |
| 43 | * |
| 44 | * foreach ($iterator as $value) { |
| 45 | * echo $value; // Outputs: 2, 4, 6, 8, 10 |
| 46 | * } |
| 47 | * ``` |
| 48 | * |
| 49 | * @since 1.0.0 |
| 50 | */ |
| 51 | class ClosureIteratorIterator extends CountableIteratorIterator |
| 52 | { |
| 53 | /** |
| 54 | * Initializes the ClosureIteratorIterator. |
| 55 | * |
| 56 | * @param iterable $iterator the underlying iterator to wrap |
| 57 | * @param Closure $closure the transformation function applied to each element |
| 58 | */ |
| 59 | public function __construct( |
| 60 | iterable $iterator, |
| 61 | private Closure $closure |
| 62 | ) { |
| 63 | parent::__construct(new IterableIterator($iterator)); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Returns the current transformed element. |
| 68 | * |
| 69 | * The closure is applied to the original current element of the iterator. |
| 70 | * |
| 71 | * @return mixed the transformed element |
| 72 | */ |
| 73 | public function current(): mixed |
| 74 | { |
| 75 | return \call_user_func($this->closure, parent::current(), parent::key()); |
| 76 | } |
| 77 | } |