PaginableArray::next()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Vvval\Spiral;
4
5
use Spiral\Core\Component;
6
use Spiral\Pagination\PaginatorAwareInterface;
7
use Spiral\Pagination\Traits\PaginatorTrait;
8
9
class PaginableArray extends Component implements \Countable, PaginatorAwareInterface, \Iterator
10
{
11
    use PaginatorTrait;
12
13
    /** @var array */
14
    protected $source = [];
15
16
    /** @var int */
17
    private $cursor;
18
19
    /** @var array */
20
    private $keys = [];
21
22
    /**
23
     * ArraySource constructor.
24
     *
25
     * @param array $source
26
     */
27
    public function __construct(array $source = [])
28
    {
29
        $this->source = $source;
30
        $this->keys = array_keys($this->source);
31
    }
32
33
    /**
34
     * @param bool $paginate
35
     * @return array
36
     */
37
    public function iterate(bool $paginate = true): array
38
    {
39
        if ($paginate && $this->hasPaginator()) {
40
            return array_slice(
41
                $this->source,
42
                $this->getPaginator()->getOffset(),
43
                $this->getPaginator()->getLimit()
44
            );
45
        }
46
47
        return $this->source;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     *
53
     * @return int
54
     */
55
    public function count(): int
56
    {
57
        return count($this->iterate(false));
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     *
63
     * @return mixed
64
     */
65
    public function current()
66
    {
67
        $offset = $this->hasPaginator() ? $this->getPaginator()->getOffset() : 0;
68
        $key = $this->keys[$this->key() + $offset];
69
70
        return $this->source[$key];
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function next()
77
    {
78
        $this->cursor++;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     *
84
     * @return
85
     */
86
    public function key(): int
87
    {
88
        return $this->cursor;
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @return bool
95
     */
96
    public function valid(): bool
97
    {
98
        return $this->key() < count($this->iterate());
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    public function rewind()
105
    {
106
        $this->cursor = 0;
107
    }
108
}