Passed
Push — 8.x-dev ( 640d34...2250ec )
by Arnaud
04:51 queued 16s
created

Section::sortSubPages()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 28
ccs 15
cts 15
cp 1
crap 3
rs 9.9
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
use Cecil\Exception\RuntimeException;
20
21
/**
22
 * Class Generator\Section.
23
 */
24
class Section extends AbstractGenerator implements GeneratorInterface
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29 1
    public function generate(): void
30
    {
31 1
        $sections = [];
32
33
        // identifying sections
34
        foreach ($this->builder->getPages() as $page) {
35 1
            /** @var Page $page */
36 1
            if ($page->getSection()) {
37
                // do not add not published and not excluded pages to its section
38 1
                if ($page->getVariable('published') !== true || $page->getVariable('exclude')) {
39 1
                    continue;
40 1
                }
41 1
                $sections[$page->getSection()][$page->getVariable('language', $this->config->getLanguageDefault())][] = $page;
42 1
            }
43
        }
44 1
45
        // adds each section to pages collection
46
        if (\count($sections) > 0) {
47
            $menuWeight = 100;
48
49 1
            foreach ($sections as $section => $languages) {
50 1
                foreach ($languages as $language => $pagesAsArray) {
51
                    $pageId = $path = Page::slugify($section);
52 1
                    if ($language != $this->config->getLanguageDefault()) {
53 1
                        $pageId = "$language/$pageId";
54 1
                    }
55 1
                    $page = (new Page($pageId))->setVariable('title', ucfirst($section))
56 1
                        ->setPath($path);
57
                    if ($this->builder->getPages()->has($pageId)) {
58 1
                        $page = clone $this->builder->getPages()->get($pageId);
59 1
                    }
60 1
                    $pages = new PagesCollection("section-$pageId", $pagesAsArray);
61 1
                    // cascade variables
62
                    if ($page->hasVariable('cascade')) {
63 1
                        $cascade = $page->getVariable('cascade');
64
                        $pages->map(function (Page $page) use ($cascade) {
65
                            foreach ($cascade as $key => $value) {
66 1
                                if (!$page->hasVariable($key)) {
67 1
                                    $page->setVariable($key, $value);
68 1
                                }
69 1
                            }
70 1
                        });
71 1
                    }
72
                    // sorts pages
73
                    $pages = self::sortSubPages($page, $pages);
74 1
                    // adds navigation links (excludes taxonomy pages)
75
                    $sortby = $page->getVariable('sortby')['variable'] ?? $page->getVariable('sortby') ?? 'date';
76
                    if (!\in_array($page->getId(), array_keys((array) $this->config->get('taxonomies')))) {
77 1
                        $this->addNavigationLinks($pages, $sortby, $page->getVariable('circular'));
78
                    }
79
                    // creates page for each section
80
                    $page->setType(Type::SECTION)
81
                        ->setSection($path)
82
                        ->setPages($pages)
83
                        ->setVariable('language', $language)
84
                        ->setVariable('date', $pages->first()->getVariable('date'))
85
                        ->setVariable('langref', $path);
86 1
                    // human readable title
87 1
                    if ($page->getVariable('title') == 'index') {
88
                        $page->setVariable('title', $section);
89 1
                    }
90 1
                    // default menu
91 1
                    if (!$page->getVariable('menu')) {
92
                        $page->setVariable('menu', ['main' => ['weight' => $menuWeight]]);
93 1
                    }
94 1
                    $this->generatedPages->add($page);
95
                }
96
                $menuWeight += 10;
97 1
            }
98
        }
99
    }
100 1
101 1
    /**
102
     * Sorts subpages.
103
     */
104 1
    public static function sortSubPages(Page $page, PagesCollection $pages): PagesCollection
105 1
    {
106 1
        // sorts (by date by default)
107 1
        $pages = $pages->sortByDate();
108 1
        /*
109 1
         * sortby: date|updated|title|weight
110
         *
111 1
         * sortby:
112 1
         *   variable: date|updated
113
         *   desc_title: false|true
114
         *   reverse: false|true
115 1
         */
116 1
        if ($page->hasVariable('sortby')) {
117
            $sortby = (string) $page->getVariable('sortby');
118 1
            // options?
119
            $sortby = $page->getVariable('sortby')['variable'] ?? $sortby;
120 1
            $descTitle = $page->getVariable('sortby')['desc_title'] ?? false;
121
            $reverse = $page->getVariable('sortby')['reverse'] ?? false;
122
            // sortby: date, title or weight
123
            $sortMethod = sprintf('sortBy%s', ucfirst(str_replace('updated', 'date', $sortby)));
124
            if (!method_exists($pages, $sortMethod)) {
125
                throw new RuntimeException(sprintf('In "%s" "%s" is not a valid value for "sortby" variable.', $page->getId(), $sortby));
126
            }
127
128 1
            return $pages->$sortMethod(['variable' => $sortby, 'descTitle' => $descTitle, 'reverse' => $reverse]);
129
        }
130 1
131 1
        return $pages;
132 1
    }
133
134 1
    /**
135 1
     * Adds navigation (next and prev) to section subpages.
136 1
     */
137
    protected function addNavigationLinks(PagesCollection $pages, string $sort = null, $circular = false): void
138 1
    {
139 1
        $pagesAsArray = $pages->toArray();
140 1
        if ($sort === null || $sort == 'date' || $sort == 'updated') {
141 1
            $pagesAsArray = array_reverse($pagesAsArray);
142 1
        }
143
        $count = \count($pagesAsArray);
144 1
        if ($count > 1) {
145 1
            foreach ($pagesAsArray as $position => $page) {
146 1
                switch ($position) {
147 1
                    case 0: // first
148 1
                        if ($circular) {
149 1
                            $page->setVariables([
150 1
                                'prev' => $pagesAsArray[$count - 1],
151 1
                            ]);
152 1
                        }
153 1
                        $page->setVariables([
154 1
                            'next' => $pagesAsArray[$position + 1],
155 1
                        ]);
156
                        break;
157 1
                    case $count - 1: // last
158
                        $page->setVariables([
159 1
                            'prev' => $pagesAsArray[$position - 1],
160 1
                        ]);
161 1
                        if ($circular) {
162 1
                            $page->setVariables([
163 1
                                'next' => $pagesAsArray[0],
164
                            ]);
165 1
                        }
166
                        break;
167
                    default:
168
                        $page->setVariables([
169
                            'prev' => $pagesAsArray[$position - 1],
170
                            'next' => $pagesAsArray[$position + 1],
171
                        ]);
172
                        break;
173
                }
174
                $this->generatedPages->add($page);
175
            }
176
        }
177
    }
178
}
179