Passed
Push — analysis-a6V9G7 ( 13bf1f )
by Arnaud
07:36 queued 03:55
created

Create::process()   F

Complexity

Conditions 17
Paths 288

Size

Total Lines 91
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 17
eloc 46
nc 288
nop 0
dl 0
loc 91
rs 3.2833
c 1
b 1
f 0

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