Completed
Push — feature-output-formats ( 361247...47e05f )
by Arnaud
02:09
created

Pagination::generate()   F

Complexity

Conditions 19
Paths 590

Size

Total Lines 102

Duplication

Lines 6
Ratio 5.88 %

Importance

Changes 0
Metric Value
dl 6
loc 102
rs 0.7355
c 0
b 0
f 0
cc 19
nc 590
nop 2

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
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Generator;
10
11
use Cecil\Collection\Page\Collection as PagesCollection;
12
use Cecil\Collection\Page\Page;
13
use Cecil\Page\Type;
14
15
/**
16
 * Class Pagination.
17
 */
18
class Pagination extends AbstractGenerator implements GeneratorInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function generate(PagesCollection $pagesCollection, \Closure $messageCallback)
24
    {
25
        $generatedPages = new PagesCollection();
26
27
        // disabled?
28
        if (false === $this->config->get('site.pagination.enabled')) {
29
            return $generatedPages;
30
        }
31
32
        // filter pages: home and sections
33
        $filteredPages = $pagesCollection->filter(function (Page $page) {
34
            return in_array($page->getType(), [Type::HOMEPAGE, Type::SECTION]);
35
        });
36
        /* @var $page Page */
37
        foreach ($filteredPages as $page) {
38
            // config
39
            $paginationPerPage = intval($this->config->get('site.pagination.max'));
40
            $paginationPath = $this->config->get('site.pagination.path');
41
            // page variables
42
            $path = $page->getPath();
43
            $pages = $page->getVariable('pages');
44
            // sort
45
            if ($sortSections = $this->config->get('site.pagination.sections')) {
46
                if (array_key_exists($page->getPath(), $sortSections)
47
                    && array_key_exists('sortby', $sortSections[$page->getPath()])
48
                ) {
49
                    switch ($sortSections[$page->getPath()]['sortby']) {
50
                        case 'weight':
51
                            $pages = $pages->sortByWeight();
52
                            break;
53
                        case 'title':
54
                            $pages = $pages->sortByTitle();
55
                            break;
56
                        case 'date':
57
                        default:
58
                            $pages = $pages->sortByDate();
59
                            break;
60
                    }
61
                }
62
            }
63
            // build pagination
64
            $pagesTotal = count($pages);
65
            if ($pagesTotal > $paginationPerPage) {
66
                $paginationPagesCount = ceil($pagesTotal / $paginationPerPage);
67
                for ($i = 0; $i < $paginationPagesCount; $i++) {
68
                    $pagesInPagination = new \LimitIterator($pages->getIterator(), ($i * $paginationPerPage), $paginationPerPage);
69
                    $pagesInPagination = new PagesCollection($page->getId().'-page-'.($i + 1), iterator_to_array($pagesInPagination));
70
                    $alteredPage = clone $page;
71
                    // first page
72
                    $firstPath = Page::slugify(sprintf('%s', $path));
73
                    if ($i == 0) {
74
                        // ie: blog + blog/page/1 (alias)
75
                        $pageId = Page::slugify(sprintf('%s', $path));
76
                        // homepage special case
77
                        if ($path == '') {
78
                            $pageId = 'index';
79
                        }
80
                        $currentPath = $firstPath;
81
                        $alteredPage
82
                            ->setId($pageId)
83
                            ->setPath($firstPath)
84
                            ->setVariable('aliases', [
85
                                sprintf('%s/%s/%s', $path, $paginationPath, 1),
86
                            ]);
87
                    } else {
88
                        // ie: blog/page/2
89
                        $pageId = Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $i + 1));
90
                        $currentPath = $pageId;
91
                        $alteredPage
92
                            ->setId($pageId)
93
                            ->setPath($currentPath)
94
                            ->unVariable('menu')
95
                            ->setVariable('paginated', true);
96
                    }
97
                    // create "pagination" variable
98
                    $pagination = [
99
                        'totalpages' => $pagesTotal,
100
                        'pages'      => $pagesInPagination,
101
                    ];
102
                    // add links
103
                    $pagination['links'] = ['self' => $currentPath ?: 'index'];
104
                    $pagination['links'] += ['first' => $firstPath ?: 'index'];
105
                    if ($i == 1) {
106
                        $pagination['links'] += ['prev' => Page::slugify($path ?: 'index')];
107
                    }
108 View Code Duplication
                    if ($i > 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
                        $pagination['links'] += ['prev' => Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $i))];
110
                    }
111 View Code Duplication
                    if ($i < $paginationPagesCount - 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
                        $pagination['links'] += ['next' => Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $i + 2))];
113
                    }
114
                    $pagination['links'] += ['last' => Page::slugify(sprintf('%s/%s/%s', $path, $paginationPath, $paginationPagesCount))];
115
                    $alteredPage->setVariable('pagination', $pagination);
116
                    // update date with the first element of the collection
117
                    $alteredPage->setVariable('date', $pagesInPagination->getIterator()->current()->getVariable('date'));
118
                    $generatedPages->add($alteredPage);
119
                }
120
            }
121
        }
122
123
        return $generatedPages;
124
    }
125
}
126