paginate()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 4
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt;
5
6
/**
7
 * Returns array pagination
8
 * If <b>page</b> or <b>per_page</b> is less than 1, this function will return empty array
9
 *
10
 * @param array $items The array to be paginated
11
 * @param int $page The page number (first page is `1`)
12
 * @param int $per_page Number of elements per page
13
 * @param bool $preserve_keys Preserve keys
14
 * @return array
15
 */
16
function paginate(array $items, int $page, int $per_page, bool $preserve_keys = true): array
17
{
18
    if ($per_page < 1 || $page < 1) {
19
        return [];
20
    }
21
22
    $offset = max(0, ($page - 1) * $per_page);
23
24
    return array_slice($items, $offset, $per_page, $preserve_keys);
25
}
26