Passed
Pull Request — master (#57)
by Stone
03:27
created

Pagination   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 34
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A getPagination() 0 21 5
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
}