Passed
Push — nested-sections ( 2d40b2...7dbf34 )
by Arnaud
12:03 queued 05:37
created

Create::createMenusFromPages()   B

Complexity

Conditions 11
Paths 14

Size

Total Lines 74
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 12.1908

Importance

Changes 0
Metric Value
cc 11
eloc 40
c 0
b 0
f 0
nc 14
nop 0
dl 0
loc 74
ccs 33
cts 42
cp 0.7856
crap 12.1908
rs 7.3166

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\Step\Menus;
15
16
use Cecil\Collection\Menu\Collection as MenusCollection;
17
use Cecil\Collection\Menu\Entry;
18
use Cecil\Collection\Menu\Menu;
19
use Cecil\Collection\Page\Page;
20
use Cecil\Exception\RuntimeException;
21
use Cecil\Logger\PrintLogger;
22
use Cecil\Renderer\Page as PageRenderer;
23
use Cecil\Step\AbstractStep;
24
25
/**
26
 * Creates menus collection.
27
 */
28
class Create extends AbstractStep
29
{
30
    /** @var array */
31
    protected $menus;
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 1
    public function getName(): string
37
    {
38 1
        return 'Creating menus';
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     *
44
     * @throws RuntimeException
45
     */
46 1
    public function process(): void
47
    {
48
        // creates a Menu collection for each language, with a default "main" menu
49 1
        foreach ($this->config->getLanguages() as $language) {
50 1
            $this->menus[$language['code']] = new MenusCollection('menus');
51 1
            $this->menus[$language['code']]->add(new Menu('main'));
52
        }
53
54
        $this->createMenusFromPages();
55 1
56
        /**
57
         * Removing/adding/replacing menus entries from config.
58
         * ie:
59
         *   menus:
60
         *     main:
61
         *       # remove
62
         *       - id: about
63
         *         enabled: false
64
         *       # add
65
         *       - id: example
66
         *         name: "Example"
67
         *         url: https://example.com
68
         *         weight: 999
69 1
         *       # replace
70 1
         *       - id: index
71 1
         *         name: "Home page"
72 1
         */
73 1
        foreach ($this->config->getLanguages() as $language) {
74 1
            if ($menusConfig = (array) $this->config->get('menus', $language['code'], false)) {
75
                $totalConfig = array_sum(array_map('count', $menusConfig));
76 1
                $countConfig = 0;
77 1
78 1
                foreach ($menusConfig as $menuConfig => $entry) {
79
                    // add Menu if not exists
80
                    if (!$this->menus[$language['code']]->has($menuConfig)) {
81 1
                        $this->menus[$language['code']]->add(new Menu($menuConfig));
82
                    }
83 1
                    /** @var \Cecil\Collection\Menu\Menu $menu */
84
                    $menu = $this->menus[$language['code']]->get($menuConfig);
85
                    foreach ($entry as $key => $properties) {
86
                        $countConfig++;
87 1
                        $updated = false;
88 1
89 1
                        // ID is required
90 1
                        if (!isset($properties['id'])) {
91 1
                            $this->builder->getLogger()->error(sprintf('Config menu entry: key "id" is required for entry at position %s in "%s" menu', $key, $menu), ['progress' => [$countConfig, $totalConfig]]);
92
                            continue;
93
                        }
94 1
                        /** @var \Cecil\Collection\Menu\Entry $item */
95
                        $item = (new Entry($properties['id']))
96
                            ->setName($properties['name'] ?? ucfirst($properties['id']))
97
                            ->setUrl($properties['url'] ?? '404')
98 1
                            ->setWeight((int) ($properties['weight'] ?? 0));
99 1
                        // is entry already exists?
100 1
                        if ($menu->has($properties['id'])) {
101
                            // removes a not enabled entry
102
                            if (isset($properties['enabled']) && $properties['enabled'] === false) {
103
                                $menu->remove($properties['id']);
104
105
                                $message = sprintf('Config menu entry "%s (%s) > %s" removed', (string) $menu, $language['code'], $properties['id']);
106 1
                                $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
107
                                continue;
108 1
                            }
109 1
                            // merges properties
110
                            $current = $menu->get($properties['id'])->toArray();
111 1
                            $properties = array_merge($current, $properties);
112 1
                            /** @var \Cecil\Collection\Menu\Entry $item */
113 1
                            $item = clone $menu->get($properties['id']);
114
                            $item->setName($properties['name'])
115
                                ->setUrl($properties['url'])
116 1
                                ->setWeight($properties['weight']);
117 1
                            $updated = true;
118 1
                        }
119
                        // adds/replaces entry
120 1
                        $menu->add($item);
121 1
122
                        $message = sprintf('Config menu entry "%s (%s) > %s" %s {name: %s, url: %s, weight: %s}', (string) $menu, $language['code'], $item->getId(), $updated ? 'updated' : 'created', $item-> getName(), $item->getUrl(), $item->getWeight());
123
                        $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
124 1
                    }
125 1
                }
126 1
            }
127 1
        }
128 1
129 1
        $this->builder->setMenus($this->menus);
130
    }
131 1
132 1
    /**
133 1
     * Create menus from pages' `menu` variable.
134
     */
135
    protected function createMenusFromPages(): void
136
    {
137
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
138
            return $page->hasVariable('menu')
139
                && $page->getVariable('published') === true
140
                && \in_array($page->getVariable('language', $this->config->getLanguageDefault()), array_column($this->config->getLanguages(), 'code'));
141 1
        });
142
143
        $total = \count($filteredPages);
144
        $count = 0;
145
        /** @var \Cecil\Collection\Page\Page $page */
146
        foreach ($filteredPages as $page) {
147 1
            $count++;
148
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
149 1
            /**
150 1
             * Array case.
151 1
             *
152 1
             * case 1:
153 1
             *   menu: [main, navigation]
154
             * case 2:
155 1
             *   menu:
156 1
             *     main:
157
             *       weight: 999
158 1
             */
159 1
            if (\is_array($page->getVariable('menu'))) {
160 1
                foreach ($page->getVariable('menu') as $key => $value) {
161
                    $menuName = $key;
162
                    $properties = $value;
163
                    if (\is_int($key)) {
164
                        $menuName = $value;
165
                        $properties = null;
166
                    }
167
                    if (!\is_string($menuName)) {
168
                        $this->builder->getLogger()->error(sprintf('Menu\'s name of page "%s" must be a string, not "%s"', $page->getId(), PrintLogger::format($menuName)), ['progress' => [$count, $total]]);
169
                        continue;
170
                    }
171 1
                    $item = (new Entry($page->getIdWithoutLang()))
172 1
                        ->setName($page->getVariable('title'))
173 1
                        ->setUrl((new PageRenderer($this->config))->getUrl($page));
174 1
                    if (isset($properties['weight'])) {
175 1
                        $item->setWeight((int) $properties['weight']);
176 1
                    }
177 1
                    // add Menu if not exists
178 1
                    if (!$this->menus[$language]->has($menuName)) {
179
                        $this->menus[$language]->add(new Menu($menuName));
180 1
                    }
181
                    /** @var \Cecil\Collection\Menu\Menu $menu */
182
                    $menu = $this->menus[$language]->get($menuName);
183
                    $menu->add($item);
184
185
                    $message = sprintf('Page menu entry "%s (%s) > %s" created {name: %s, weight: %s}', $menu->getId(), $language, $item->getId(), $item->getName(), $properties['weight'] ?? 'N/A');
186
                    $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
187
                }
188
                continue;
189
            }
190
            /**
191 1
             * String case.
192 1
             *
193 1
             * e.g.:
194 1
             *   menu: main
195 1
             */
196 1
            $item = (new Entry($page->getIdWithoutLang()))
197
                ->setName($page->getVariable('title'))
198
                ->setUrl((new PageRenderer($this->config))->getUrl($page));
199 1
            // add Menu if not exists
200 1
            if (!$this->menus[$language]->has($page->getVariable('menu'))) {
201
                $this->menus[$language]->add(new Menu($page->getVariable('menu')));
202
            }
203 1
            /** @var \Cecil\Collection\Menu\Menu $menu */
204 1
            $menu = $this->menus[$language]->get($page->getVariable('menu'));
205
            $menu->add($item);
206 1
207 1
            $message = sprintf('Page menu entry "%s (%s) > %s" created {name: %s}', $menu->getId(), $language, $item->getId(), $item->getName());
208
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
209 1
        }
210
    }
211
}
212