Passed
Push — analysis-9bxEgn ( 78bf13 )
by Arnaud
03:56 queued 10s
created

Create::process()   D

Complexity

Conditions 16
Paths 192

Size

Total Lines 96
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
cc 16
eloc 49
c 3
b 2
f 0
nc 192
nop 0
dl 0
loc 96
rs 4.8

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