Passed
Pull Request — master (#1704)
by Arnaud
10:00 queued 04:05
created

Pagination::generate()   D

Complexity

Conditions 20
Paths 95

Size

Total Lines 118
Code Lines 81

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 86
CRAP Score 20.0153

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 20
eloc 81
c 1
b 1
f 0
nc 95
nop 0
dl 0
loc 118
ccs 86
cts 89
cp 0.9663
crap 20.0153
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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->value, Type::SECTION->value, Type::TERM->value]);
37 1
        });
38
        /** @var Page $page */
39 1
        foreach ($filteredPages as $page) {
40
            // if no sub-pages: by-pass
41 1
            if ($page->getPages() === null) {
42 1
                continue;
43
            }
44 1
            $pages = $page->getPages()->filter(function (Page $page) {
45 1
                return $page->getType() == Type::PAGE->value && $page->getVariable('published');
46 1
            });
47
            // if no published sub-pages: by-pass
48 1
            if ($pages === null) {
49
                continue;
50
            }
51 1
            $path = $page->getPath();
52
            // site pagination configuration
53 1
            $paginationPerPage = \intval($this->config->get('pagination.max') ?? 5);
54 1
            $paginationPath = (string) $this->config->get('pagination.path') ?? 'page';
55
            // page pagination configuration
56 1
            $pagePagination = $page->getVariable('pagination');
57 1
            if ($pagePagination) {
58 1
                if (isset($pagePagination['enabled']) && $pagePagination['enabled'] === false) {
59
                    continue;
60
                }
61 1
                if (isset($pagePagination['max'])) {
62 1
                    $paginationPerPage = \intval($pagePagination['max']);
63
                }
64 1
                if (isset($pagePagination['path'])) {
65 1
                    $paginationPath = (string) $pagePagination['path'];
66
                }
67
            }
68 1
            $pagesTotal = \count($pages);
69
            // is pagination not necessary?
70 1
            if ($pagesTotal <= $paginationPerPage) {
71 1
                continue;
72
            }
73
            // sorts pages
74 1
            $pages = Section::sortSubPages($this->config, $page, $pages);
75
            // builds paginator
76 1
            $paginatorPagesCount = \intval(ceil($pagesTotal / $paginationPerPage));
77 1
            for ($i = 0; $i < $paginatorPagesCount; $i++) {
78 1
                $itPagesInPagination = new \LimitIterator($pages->getIterator(), $i * $paginationPerPage, $paginationPerPage);
79 1
                $pagesInPagination = new PagesCollection(
80 1
                    $page->getId() . '-page-' . ($i + 1),
81 1
                    iterator_to_array($itPagesInPagination)
82 1
                );
83 1
                $alteredPage = clone $page;
84 1
                if ($i == 0) { // first page (ie: blog/page/1 -> blog)
85 1
                    $pageId = $page->getId();
86 1
                    $alteredPage
87 1
                        ->setVariable('alias', [
88 1
                            sprintf('%s/%s/%s', $path, $paginationPath, 1),
89 1
                        ]);
90
                } else { // others pages (ie: blog/page/X)
91 1
                    $pageId = Page::slugify(sprintf('%s/%s/%s', $page->getId(), $paginationPath, $i + 1));
92 1
                    $alteredPage
93 1
                        ->setId($pageId)
94 1
                        ->setVirtual(true)
95 1
                        ->setPath(Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $i + 1)))
96 1
                        ->unVariable('menu')
97 1
                        ->unVariable('alias')
98 1
                        ->unVariable('aliases') // backward compatibility
99 1
                        ->unVariable('langref')
100 1
                        ->setVariable('paginated', true);
101
                }
102
                // set paginator values
103 1
                $paginator = [
104 1
                    'pages'       => $pagesInPagination,
105 1
                    'pages_total' => $pagesTotal,
106 1
                    'totalpages'  => $pagesTotal, // backward compatibility
107 1
                    'count'       => $paginatorPagesCount,
108 1
                    'current'     => $i + 1,
109 1
                ];
110
                // adds links
111 1
                $paginator['links'] = ['first' => $page->getId() ?: 'index'];
112 1
                if ($i == 1) {
113 1
                    $paginator['links'] += ['prev' => $page->getId() ?: 'index'];
114
                }
115 1
                if ($i > 1) {
116 1
                    $paginator['links'] += ['prev' => Page::slugify(sprintf(
117 1
                        '%s/%s/%s',
118 1
                        $page->getId(),
119 1
                        $paginationPath,
120 1
                        $i
121 1
                    ))];
122
                }
123 1
                $paginator['links'] += ['self' => $pageId ?: 'index'];
124 1
                if ($i < $paginatorPagesCount - 1) {
125 1
                    $paginator['links'] += ['next' => Page::slugify(sprintf(
126 1
                        '%s/%s/%s',
127 1
                        $page->getId(),
128 1
                        $paginationPath,
129 1
                        $i + 2
130 1
                    ))];
131
                }
132 1
                $paginator['links'] += ['last' => Page::slugify(sprintf(
133 1
                    '%s/%s/%s',
134 1
                    $page->getId(),
135 1
                    $paginationPath,
136 1
                    $paginatorPagesCount
137 1
                ))];
138 1
                $paginator['links'] += ['path' => Page::slugify(sprintf('%s/%s', $page->getId(), $paginationPath))];
139
                // set paginator to cloned page
140 1
                $alteredPage->setPaginator($paginator);
141 1
                $alteredPage->setVariable('pagination', $paginator); // backward compatibility
142
                // updates date with the first element of the collection
143 1
                $alteredPage->setVariable('date', $pagesInPagination->first()->getVariable('date'));
144
145 1
                $this->generatedPages->add($alteredPage);
146
            }
147
        }
148
    }
149
}
150