Passed
Push — master ( 43fd43...f7d7a3 )
by Smoren
02:05
created

DynamicSequence   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 12
c 1
b 0
f 1
dl 0
loc 50
ccs 12
cts 12
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getNextValue() 0 3 1
A getValueByIndex() 0 9 2
A __construct() 0 9 1
1
<?php
2
3
namespace Smoren\Sequence\Structs;
4
5
use function Smoren\Sequence\Functions\reduce;
6
use function Smoren\Sequence\Functions\xrange;
7
8
/**
9
 * Implementation of sequence configured with callables.
10
 *
11
 * @template T
12
 * @extends Sequence<T>
13
 */
14
class DynamicSequence extends Sequence
15
{
16
    /**
17
     * @var callable(T $previousValue): T getter for the next value
18
     */
19
    protected $nextValueGetter;
20
    /**
21
     * @var (callable(int $index, T $start): T)|null getter for the i-th value
0 ignored issues
show
Documentation Bug introduced by
The doc comment (callable(int at position 1 could not be parsed: Expected ')' at position 1, but found 'callable'.
Loading history...
22
     */
23
    protected $indexValueGetter;
24
25
    /**
26
     * StepSequence constructor.
27
     *
28
     * @param T $start start of the sequence
29
     * @param int<0, max>|null $size size of the sequence (infinite if null)
30
     * @param callable(T $previousValue): T $nextValueGetter getter for the next value
31
     * @param (callable(int $index, T $start): T)|null $indexValueGetter getter for the i-th value
0 ignored issues
show
Documentation Bug introduced by
The doc comment (callable(int at position 1 could not be parsed: Expected ')' at position 1, but found 'callable'.
Loading history...
32
     */
33 8
    public function __construct(
34
        $start,
35
        ?int $size,
36
        callable $nextValueGetter,
37
        ?callable $indexValueGetter = null
38
    ) {
39 8
        parent::__construct($start, $size);
40 8
        $this->nextValueGetter = $nextValueGetter;
41 8
        $this->indexValueGetter = $indexValueGetter;
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47 8
    public function getNextValue($previousValue)
48
    {
49 8
        return ($this->nextValueGetter)($previousValue);
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     */
55 8
    public function getValueByIndex(int $index)
56
    {
57 8
        if(is_callable($this->indexValueGetter)) {
58 5
            return ($this->indexValueGetter)($index, $this->start);
59
        }
60
61 3
        return reduce(xrange($index), function($carry) {
62 3
            return $this->getNextValue($carry);
63 3
        }, $this->start);
64
    }
65
}
66