Completed
Push — master ( c3b775...3173eb )
by Derek Stephen
01:53
created

PaginationFilter::filter()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 17
cts 17
cp 1
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 17
nc 6
nop 1
crap 8
1
<?php
2
3
namespace Del\Filter\Filter;
4
5
use ArrayIterator;
6
use LogicException;
7
8
class PaginationFilter implements FilterInterface
9
{
10
    /** @var int $page */
11
    private $page;
12
13
    /** @var int $numPerPage */
14
    private $numPerPage;
15
16
    /**
17
     * @param ArrayIterator $collection
18
     * @return ArrayIterator
19
     */
20 2
    public function filter(ArrayIterator $collection): ArrayIterator
21
    {
22
        // If pagination wasnt set, dont use it!
23 2
        if (!$this->page || !$this->numPerPage) {
24 1
            return $collection;
25
        }
26
27 1
        $results = new ArrayIterator();
28 1
        $collection->rewind();
29
30 1
        $totalRecords = $collection->count();
31 1
        $resultsOffset = ($this->page * $this->numPerPage) - $this->numPerPage;
32 1
        $resultsEndOffset = $resultsOffset + $this->numPerPage;
33
34 1
        if ($resultsOffset > $totalRecords) {
35 1
            throw new LogicException('There aren\'t that many pages for this result set.');
36
        }
37
38 1
        for ($x = 0; $x < $totalRecords; $x ++) {
39 1
            if ($collection->valid()) {
40 1
                $row = $collection->current();
41 1
                if ($x >= $resultsOffset && $x < $resultsEndOffset) {
42 1
                    $results->append($row);
43
                }
44 1
                $collection->next();
45
            }
46
        }
47
48 1
        return $results;
49
    }
50
51
    /**
52
     * @return int
53
     */
54 1
    public function getPage(): int
55
    {
56 1
        return $this->page;
57
    }
58
59
    /**
60
     * @param int $page
61
     * @return PaginationFilter
62
     */
63 1
    public function setPage(int $page): PaginationFilter
64
    {
65 1
        $this->page = $page;
66 1
        return $this;
67
    }
68
69
    /**
70
     * @return int
71
     */
72 1
    public function getNumPerPage(): int
73
    {
74 1
        return $this->numPerPage;
75
    }
76
77
    /**
78
     * @param int $numPerPage
79
     * @return PaginationFilter
80
     */
81 1
    public function setNumPerPage(int $numPerPage): PaginationFilter
82
    {
83 1
        $this->numPerPage = $numPerPage;
84 1
        return $this;
85
    }
86
}