Passed
Pull Request — master (#1822)
by Arnaud
08:29 queued 03:25
created

Pagination   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Test Coverage

Coverage 95.51%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 82
c 4
b 1
f 0
dl 0
loc 122
ccs 85
cts 89
cp 0.9551
rs 10
wmc 19

1 Method

Rating   Name   Duplication   Size   Complexity  
D generate() 0 117 19
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Generator;
15
16
use Cecil\Collection\Page\Collection as PagesCollection;
17
use Cecil\Collection\Page\Page;
18
use Cecil\Collection\Page\Type;
19
20
/**
21
 * Class Generator\Pagination.
22
 */
23
class Pagination extends AbstractGenerator implements GeneratorInterface
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28 1
    public function generate(): void
29
    {
30 1
        if ($this->config->get('pagination.enabled') === false) {
31
            return;
32
        }
33
34
        // filters list pages (home, sections and terms)
35 1
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
36 1
            return \in_array($page->getType(), [Type::HOMEPAGE, Type::SECTION, Type::TERM]);
37 1
        });
38
        /** @var Page $page */
39 1
        foreach ($filteredPages as $page) {
40 1
            if ($page->getPages() === null) {
41
                return;
42
            }
43 1
            $pages = $page->getPages()->filter(function (Page $page) {
44 1
                return $page->getVariable('published');
45 1
            });
46
            // if no sub-pages: by-pass
47 1
            if ($pages === null) {
48
                continue;
49
            }
50 1
            $path = $page->getPath();
51
            // site pagination configuration
52 1
            $paginationPerPage = \intval($this->config->get('pagination.max') ?? 5);
53 1
            $paginationPath = (string) $this->config->get('pagination.path') ?? 'page';
54
            // page pagination configuration
55 1
            $pagePagination = $page->getVariable('pagination');
56 1
            if ($pagePagination) {
57 1
                if (isset($pagePagination['enabled']) && $pagePagination['enabled'] === false) {
58
                    continue;
59
                }
60 1
                if (isset($pagePagination['max'])) {
61 1
                    $paginationPerPage = \intval($pagePagination['max']);
62
                }
63 1
                if (isset($pagePagination['path'])) {
64 1
                    $paginationPath = (string) $pagePagination['path'];
65
                }
66
            }
67 1
            $pagesTotal = \count($pages);
68
            // is pagination not necessary?
69 1
            if ($pagesTotal <= $paginationPerPage) {
70 1
                continue;
71
            }
72
            // sorts pages
73 1
            $pages = Section::sortSubPages($page, $pages);
74
            // builds paginator
75 1
            $paginatorPagesCount = \intval(ceil($pagesTotal / $paginationPerPage));
76 1
            for ($i = 0; $i < $paginatorPagesCount; $i++) {
77 1
                $itPagesInPagination = new \LimitIterator($pages->getIterator(), $i * $paginationPerPage, $paginationPerPage);
78 1
                $pagesInPagination = new PagesCollection(
79 1
                    $page->getId() . '-page-' . ($i + 1),
80 1
                    iterator_to_array($itPagesInPagination)
81 1
                );
82 1
                $alteredPage = clone $page;
83 1
                if ($i == 0) { // first page (ie: blog/page/1 -> blog)
84 1
                    $pageId = $page->getId();
85 1
                    $alteredPage
86 1
                        ->setVariable('alias', [
87 1
                            sprintf('%s/%s/%s', $path, $paginationPath, 1),
88 1
                        ]);
89
                } else { // others pages (ie: blog/page/X)
90 1
                    $pageId = Page::slugify(sprintf('%s/%s/%s', $page->getId(), $paginationPath, $i + 1));
91 1
                    $alteredPage
92 1
                        ->setId($pageId)
93 1
                        ->setVirtual(true)
94 1
                        ->setPath(Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $i + 1)))
95 1
                        ->unVariable('menu')
96 1
                        ->unVariable('alias')
97 1
                        ->unVariable('aliases') // backward compatibility
98 1
                        ->unVariable('langref')
99 1
                        ->setVariable('paginated', true);
100
                }
101
                // set paginator values
102 1
                $paginator = [
103 1
                    'pages'       => $pagesInPagination,
104 1
                    'pages_total' => $pagesTotal,
105 1
                    'totalpages'  => $pagesTotal, // backward compatibility
106 1
                    'count'       => $paginatorPagesCount,
107 1
                    'current'     => $i + 1,
108 1
                ];
109
                // adds links
110 1
                $paginator['links'] = ['first' => $page->getId() ?: 'index'];
111 1
                if ($i == 1) {
112 1
                    $paginator['links'] += ['prev' => $page->getId() ?: 'index'];
113
                }
114 1
                if ($i > 1) {
115 1
                    $paginator['links'] += ['prev' => Page::slugify(sprintf(
116 1
                        '%s/%s/%s',
117 1
                        $page->getId(),
118 1
                        $paginationPath,
119 1
                        $i
120 1
                    ))];
121
                }
122 1
                $paginator['links'] += ['self' => $pageId ?: 'index'];
123 1
                if ($i < $paginatorPagesCount - 1) {
124 1
                    $paginator['links'] += ['next' => Page::slugify(sprintf(
125 1
                        '%s/%s/%s',
126 1
                        $page->getId(),
127 1
                        $paginationPath,
128 1
                        $i + 2
129 1
                    ))];
130
                }
131 1
                $paginator['links'] += ['last' => Page::slugify(sprintf(
132 1
                    '%s/%s/%s',
133 1
                    $page->getId(),
134 1
                    $paginationPath,
135 1
                    $paginatorPagesCount
136 1
                ))];
137 1
                $paginator['links'] += ['path' => Page::slugify(sprintf('%s/%s', $page->getId(), $paginationPath))];
138
                // set paginator to cloned page
139 1
                $alteredPage->setPaginator($paginator);
140 1
                $alteredPage->setVariable('pagination', $paginator); // backward compatibility
141
                // updates date with the first element of the collection
142 1
                $alteredPage->setVariable('date', $pagesInPagination->first()->getVariable('date'));
143
144 1
                $this->generatedPages->add($alteredPage);
145
            }
146
        }
147
    }
148
}
149