Passed
Pull Request — master (#58)
by Stone
04:29 queued 02:04
created

Pagination::getPagination()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 4
nop 3
dl 0
loc 21
rs 9.4888
c 0
b 0
f 0
1
<?php
2
3
namespace Core\Modules;
4
5
use Core\Constant;
6
use Core\Traits\StringFunctions;
7
8
class Pagination extends Module
9
{
10
11
    use StringFunctions;
12
13
    /**
14
     * gets the pagination and returns the required information to set up previous / next pages
15
     * @param string $page the page number in format "page-1"
16
     * @param int $totalRows the total number of rows
17
     * @param int $rowsPerPage the number of rows per page, by default, grabbed from the core constant file
18
     * @return array the page number, the offset and the page total.
19
     * @throws \Exception
20
     */
21
    public function getPagination(string $page, int $totalRows, int $rowsPerPage = Constant::POSTS_PER_PAGE): array
22
    {
23
        $page = strtolower($page);
24
        if (!$this->startsWith($page, "page-")) {
25
            throw new \Exception("Pagination Error", "404");
26
        }
27
        $pageNo = $this->removeFromBeginning($page, "page-");
28
        if (!filter_var($pageNo, FILTER_VALIDATE_INT)) {
29
            throw new \Exception("Invalid page number");
30
        }
31
        $offset = ($pageNo - 1) * $rowsPerPage;
32
        $totalPages = ceil($totalRows / $rowsPerPage);
33
34
        if ($pageNo > $totalPages && $totalPages != 0) {
35
            throw new \Error("Pagination Number not found", "404");
36
        }
37
38
        return array(
39
            "pageNo" => $pageNo,
40
            "offset" => $offset,
41
            "totalPages" => $totalPages
42
        );
43
    }
44
}