Completed
Push — master ( bbcf4b...c3b775 )
by Derek Stephen
01:35
created

PaginationFilter::filter()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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