Completed
Pull Request — master (#182)
by Max
12:48 queued 10:19
created

ValidTernary::value()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 8
rs 10
1
<?php
2
3
namespace MaxGoryunov\SavingIterator\Src;
4
5
use Closure;
6
use Iterator;
7
8
/**
9
 * Class which checks whether the given iterator is valid and calls consequent
10
 * path if it is true and alternate path otherwise.
11
 * @template T
12
 * @implements Scalar<T>
13
 */
14
final class ValidTernary implements Scalar
15
{
16
    /**
17
     * Ctor.
18
     *
19
     * @template TKey
20
     * @template TValue
21
     * @phpstan-param Iterator<TKey, TValue> $origin
22
     * @phpstan-param Closure(Iterator<TKey, TValue>):T $cons
23
     * @phpstan-param Closure(Iterator<TKey, TValue>):T $alter
24
     * @param Iterator $origin iterator which validity is checked.
25
     * @param Closure $cons    consequent path if iterator is valid.
26
     * @param Closure $alter   alternative path if iterator is not valid.
27
     */
28
    public function __construct(
29
        /**
30
         * Iterator which validity is checked.
31
         *
32
         * @phpstan-var Iterator<TKey, TValue>
33
         * @var Iterator
34
         */
35
        private Iterator $origin,
36
37
        /**
38
         * Consequent path if iterator is valid.
39
         *
40
         * @phpstan-var Closure(Iterator<TKey, TValue>):T
41
         * @var Closure
42
         */
43
        private Closure $cons,
44
45
        /**
46
         * Alternate path if iterator is not valid.
47
         *
48
         * @phpstan-var Closure(Iterator<TKey, TValue>):T
49
         * @var Closure
50
         */
51
        private Closure $alter
52
    ) {
53
    }
54
55
    public function value(): mixed
56
    {
57
        if ($this->origin->valid()) {
58
            $path = $this->cons;
59
        } else {
60
            $path = $this->alter;
61
        }
62
        return $path($this->origin);
63
    }
64
}
65