1: <?php declare(strict_types=1);
2:
3: namespace Salient\Iterator;
4:
5: use Salient\Utility\Get;
6: use Closure;
7: use IteratorIterator;
8: use ReturnTypeWillChange;
9: use Traversable;
10:
11: /**
12: * Iterates over an iterator, applying a callback to values as they are returned
13: *
14: * @api
15: *
16: * @template TKey
17: * @template TInput
18: * @template TOutput
19: *
20: * @extends IteratorIterator<TKey,TOutput,Traversable<TKey,TInput>>
21: */
22: class MapIterator extends IteratorIterator
23: {
24: /** @var Closure(TInput, TKey, Traversable<TKey,TInput>): TOutput */
25: private Closure $Callback;
26:
27: /**
28: * @param Traversable<TKey,TInput> $iterator
29: * @param callable(TInput, TKey, Traversable<TKey,TInput>): TOutput $callback
30: */
31: public function __construct(Traversable $iterator, callable $callback)
32: {
33: $this->Callback = Get::closure($callback);
34:
35: parent::__construct($iterator);
36: }
37:
38: /**
39: * @return TOutput
40: * @disregard P1038
41: */
42: #[ReturnTypeWillChange]
43: public function current()
44: {
45: /** @var TInput */
46: $current = parent::current();
47: return ($this->Callback)($current, $this->key(), $this);
48: }
49: }
50: