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

Circular   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 20
c 2
b 0
f 0
dl 0
loc 61
ccs 16
cts 20
cp 0.8
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A value() 0 9 3
A refineData() 0 12 3
A __invoke() 0 3 1
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