Completed
Push — master ( 163f0d...68c250 )
by Derek Stephen
01:38
created

PaginationFilter::filter()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 1
crap 4
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
        $totalRecords = $collection->count();
28 1
        $resultsOffset = ($this->page * $this->numPerPage) - $this->numPerPage;
29 1
        $resultsEndOffset = $resultsOffset + $this->numPerPage;
30
31 1
        if ($resultsOffset > $totalRecords) {
32 1
            throw new LogicException('There aren\'t that many pages for this result set.');
33
        }
34
35 1
        $results = $this->getResults($collection, $totalRecords, $resultsOffset, $resultsEndOffset);
36
37 1
        return $results;
38
    }
39
40 1
    private function getResults(ArrayIterator $collection, int $totalRecords, int $resultsOffset, int $resultsEndOffset)
41
    {
42 1
        $results = new ArrayIterator();
43
44 1
        $collection->rewind();
45
46 1
        for ($x = 0; $x < $totalRecords; $x ++) {
47 1
            if ($collection->valid()) {
48 1
                $row = $collection->current();
49 1
                if ($x >= $resultsOffset && $x < $resultsEndOffset) {
50 1
                    $results->append($row);
51
                }
52 1
                $collection->next();
53
            }
54
        }
55 1
        return $results;
56
    }
57
58
59
    /**
60
     * @return int
61
     */
62 1
    public function getPage(): int
63
    {
64 1
        return $this->page;
65
    }
66
67
    /**
68
     * @param int $page
69
     * @return PaginationFilter
70
     */
71 1
    public function setPage(int $page): PaginationFilter
72
    {
73 1
        $this->page = $page;
74 1
        return $this;
75
    }
76
77
    /**
78
     * @return int
79
     */
80 1
    public function getNumPerPage(): int
81
    {
82 1
        return $this->numPerPage;
83
    }
84
85
    /**
86
     * @param int $numPerPage
87
     * @return PaginationFilter
88
     */
89 1
    public function setNumPerPage(int $numPerPage): PaginationFilter
90
    {
91 1
        $this->numPerPage = $numPerPage;
92 1
        return $this;
93
    }
94
}