Passed
Push — master ( 93ee33...95960a )
by Alec
11:11 queued 10s
created

Circular::value()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core;
6
7
class Circular
8
{
9
    /** @var mixed */
10
    protected $data;
11
12
    /** @var bool */
13
    protected $oneElement = false;
14
15
    /** @var int */
16
    protected $idx = -1; // To pass tests written before
17
18
    /** @var int */
19
    protected $length = 0;
20
21
    /**
22
     * Circular constructor.
23
     * @param array $data
24
     */
25 28
    public function __construct(array $data)
26
    {
27 28
        $this->data = $this->refineData($data);
28 28
    }
29
30
    /**
31
     * @param array $data
32
     * @return mixed
33
     */
34 28
    protected function refineData(array $data)
35
    {
36 28
        $this->length = count($data);
37 28
        if (1 === $this->length) {
38 28
            $this->oneElement = true;
39 28
            return reset($data);
40
        }
41 21
        if (0 === $this->length) {
42
            $this->oneElement = true;
43
            return null;
44
        }
45 21
        return $data;
46
    }
47
48
    /**
49
     * @return mixed
50
     */
51
    public function __invoke()
52
    {
53
        return $this->value();
54
    }
55
56
    /**
57
     * @return mixed
58
     */
59 25
    public function value()
60
    {
61 25
        if ($this->oneElement) {
62 25
            return $this->data;
63
        }
64 20
        if (++$this->idx === $this->length) {
65 16
            $this->idx = 0;
66
        }
67 20
        return $this->data[$this->idx];
68
    }
69
}
70