Passed
Push — master ( 0ae7b4...3821e6 )
by Sergey
02:08
created

PaginatorTwigExtension   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 49
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
B generatePaginationData() 0 37 7
A getName() 0 2 1
A getFunctions() 0 3 1
1
<?php
2
3
namespace Morozgrafix\Twig\Extension;
4
5
use Twig\Extension\AbstractExtension;
6
use Twig\TwigFunction;
7
8
/**
9
 * Twig extension to help generate simple paginations.
10
 */
11
class PaginatorTwigExtension extends AbstractExtension {
12
13 1
	public function getName() {
14 1
			return 'paginator';
15
	}
16
17 1
	public function getFunctions() {
18
			return [
19 1
					new TwigFunction('paginator', [$this, 'generatePaginationData']),
20
			];
21
	}
22
23 8
	public function generatePaginationData(int $curr_page, int $last_page, int $num_items = 7, string $separator = '...') {
24
		// number of items needs to be an even number for better layout
25
		// rounding to nearest even number
26 8
		if ($num_items % 2 == 0) {
27 1
			$num_items++;
28
		}
29
30 8
		$pagination = [];
31
		// if total number of pages less or equal to number of items
32 8
		if ($last_page <= $num_items) {
33 3
			$pagination = range(1, $last_page);
34
		// otherwise calculate pagination array
35
		} else {
36
			// minimum number of items is 7
37 5
			if ($num_items < 7) {
38 1
				$num_items = 7;
39
			}
40
			// if current page is in the beginning return pagination with added end separator and last page
41 5
			if ($curr_page < ($num_items - 2)) {
42 3
				$pagination = array_merge($pagination, range(1, $num_items - 2));
43 3
				$pagination[] = $separator;
44 3
				$pagination[] = $last_page;
45
			// if current page in the middle return first page, front separator, pagination, end separator, last page
46 2
			} elseif (($curr_page > ($num_items - 3)) && ($curr_page < ($last_page - 3))) {
47 1
				$pagination[] = 1;
48 1
				$pagination[] = $separator;
49 1
				$pagination = array_merge($pagination, range($curr_page - ($num_items - 5) / 2, $curr_page + ($num_items - 5) / 2));
50 1
				$pagination[] = $separator;
51 1
				$pagination[] = $last_page;
52
			// if current page at the end return first page, front separator and rest of pagination
53
			} else {
54 1
				$pagination[] = 1;
55 1
				$pagination[] = $separator;
56 1
				$pagination = array_merge($pagination, range($last_page - $num_items + 3, $last_page));
57
			}
58
		}
59 8
		return array('curr_page' => $curr_page, 'last_page' => $last_page, 'num_items' => $num_items, 'separator' => $separator, 'pagination' => $pagination);
60
	}
61
}
62