Passed
Pull Request — master (#1855)
by Arnaud
09:15 queued 03:41
created

Create::process()   C

Complexity

Conditions 14
Paths 64

Size

Total Lines 82
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 14.0227

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 40
c 1
b 0
f 0
nc 64
nop 0
dl 0
loc 82
ccs 39
cts 41
cp 0.9512
crap 14.0227
rs 6.2666

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