SavingIterator::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 3
Metric Value
cc 2
eloc 12
c 8
b 1
f 3
nc 1
nop 2
dl 0
loc 23
rs 9.8666
1
<?php
2
3
namespace MaxGoryunov\SavingIterator\Src;
4
5
use Closure;
6
use Iterator;
7
use Generator;
8
9
/**
10
 * Iterator which stores iterated values.
11
 * @template TKey
12
 * @template TValue
13
 * @extends IteratorEnvelope<TKey, TValue>
14
 */
15
final class SavingIterator extends IteratorEnvelope
16
{
17
    /**
18
     * Ctor.
19
     * 
20
     * @phpstan-param Iterator<TKey, TValue>|Closure():Generator<TKey, TValue, void, void> $origin
21
     * @phpstan-param AddingIterator<TKey, TValue> $target
22
     * @param Iterator|Closure $origin original iterator.
23
     * @param AddingIterator   $target iterator to which the values are saved.
24
     */
25
    public function __construct(
26
        Iterator|Closure $origin,
27
        AddingIterator $target
28
    ) {
29
        /**
30
         * @todo #194:15min README has to show that it is now possible to 
31
         *  directly pass Generator Closures into constructor without 
32
         *  having to manually call them.
33
         */
34
        parent::__construct(
35
            /** @phpstan-ignore-next-line */
36
            new ContextVeil(
37
                $target,
38
                new ClosureReaction(
39
                    fn (AddingIterator $stored) => (new ValidTernary(
40
                        ($origin instanceof Closure) ? $origin() : $origin,
41
                        function (Iterator $source) use ($stored) {
42
                            $temp = $stored->from($source);
43
                            $source->next();
44
                            return $temp;
45
                        },
46
                        fn () => $stored
47
                    ))->value()
48
                )
49
            )
50
        );
51
    }
52
}
53