SavingIterator   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 19
Bugs 3 Features 6
Metric Value
eloc 14
c 19
b 3
f 6
dl 0
loc 40
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 30 2
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
 * 
12
 * @template TKey
13
 * @template TValue
14
 * @extends IteratorEnvelope<TKey, TValue>
15
 */
16
final class SavingIterator extends IteratorEnvelope
17
{
18
    /**
19
     * Ctor.
20
     * 
21
     * @phpstan-param Iterator<TKey, TValue>|Closure():Generator<TKey, TValue, void, void> $origin
22
     * @phpstan-param AddingIterator<TKey, TValue> $target
23
     * @param Iterator|Closure $origin original iterator.
24
     * @param AddingIterator   $target iterator to which the values are saved.
25
     */
26
    public function __construct(
27
        Iterator|Closure $origin,
28
        AddingIterator $target = new ArrayAddingIterator()
29
    ) {
30
        $reorigin = ($origin instanceof Closure) ? $origin() : $origin;
31
        parent::__construct(
32
            /** @phpstan-ignore-next-line */
33
            new ContextVeil(
34
                $target,
35
                /**
36
                 * @todo #196:60min There are phpstan issues with
37
                 *  ClosureReaction here and in ContextVeilTest. Now they are
38
                 *  fixed by ignore-line stubs but need to be fixed according
39
                 *  to phpstan ruleset.
40
                 */
41
                /** @phpstan-ignore-next-line */
42
                new ClosureReaction(
43
                    /**
44
                     * @phpstan-param AddingIterator<TKey, TValue> $stored
45
                     * Iterator for value storage.
46
                     */
47
                    fn (AddingIterator $stored) => (new ValidTernary(
48
                        $reorigin,
49
                        function (Iterator $source) use ($stored) {
50
                            $temp = $stored->from($source);
51
                            $source->next();
52
                            return $temp;
53
                        },
54
                        fn () => $stored
55
                    ))->value()
56
                )
57
            )
58
        );
59
    }
60
}
61