Passed
Push — menu ( fa9a7e )
by Arnaud
03:37
created

MenusCreate::process()   D

Complexity

Conditions 16
Paths 192

Size

Total Lines 92
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 16.1576

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 16
eloc 46
nc 192
nop 0
dl 0
loc 92
ccs 43
cts 47
cp 0.9149
crap 16.1576
rs 4.8
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
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Step;
12
13
use Cecil\Collection\Menu\Collection as MenusCollection;
14
use Cecil\Collection\Menu\Entry;
15
use Cecil\Collection\Menu\Menu;
16
use Cecil\Collection\Page\Page;
17
use Cecil\Exception\Exception;
18
use Cecil\Logger\PrintLogger;
19
use Cecil\Renderer\Page as PageRenderer;
20
21
/**
22
 * Creates menus collection.
23
 */
24
class MenusCreate extends AbstractStep
25
{
26
    /** @var array */
27
    protected $menus;
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function getName(): string
33 1
    {
34
        return 'Creating menus';
35 1
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function process()
41 1
    {
42
        // creates a 'menus' collection for each language, with a default 'main' menu
43
        foreach ($this->config->getLanguages() as $language) {
44 1
            $this->menus[$language['code']] = new MenusCollection('menus');
45 1
            $this->menus[$language['code']]->add(new Menu('main'));
46 1
        }
47 1
48
        // collects 'menu' entries from pages
49
        $this->collectPages();
50
51 1
        /**
52
         * Removing/adding/replacing menus entries from config.
53
         * ie:
54
         *   menus:
55
         *     main:
56
         *       - id: example
57
         *         name: "Example"
58
         *         url: https://example.com
59
         *         weight: 999
60
         *       - id: about
61
         *         enabled: false
62
         */
63
        foreach ($this->config->getLanguages() as $language) {
64
            if ($menusConfig = $this->config->get('menus', $language['code'], false)) {
65 1
                $this->builder->getLogger()->debug('Creating menus from config');
66 1
67 1
                $totalConfig = array_sum(array_map('count', $menusConfig));
68
                $countConfig = 0;
69 1
                $suffix = $language['code'] !== $this->config->getLanguageDefault() ? "." . $language['code'] : '';
70 1
71 1
                foreach ($menusConfig as $menuConfig => $entry) {
72
                    // add Menu if not exists
73 1
                    if (!$this->menus[$language['code']]->has($menuConfig)) {
74 1
                        $this->menus[$language['code']]->add(new Menu($menuConfig));
75
                    }
76
                    /** @var \Cecil\Collection\Menu\Menu $menu */
77
                    $menu = $this->menus[$language['code']]->get($menuConfig);
78 1
                    foreach ($entry as $key => $property) {
79 1
                        $countConfig++;
80 1
                        $enabled = true;
81 1
                        $updated = false;
82 1
83
                        // ID is required
84
                        if (!array_key_exists('id', $property)) {
85 1
                            throw new Exception(sprintf('"id" is required for entry at position %s in "%s" menu', $key, $menu));
86
                        }
87
                        // enabled?
88
                        if (array_key_exists('enabled', $property) && false === $property['enabled']) {
89 1
                            $enabled = false;
90 1
                            if (!$menu->has($property['id'])) {
91 1
                                $message = sprintf('%s > %s%s (disabled)', (string) $menu, $property['id'], $suffix);
92
                                $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
93
                            }
94
                        }
95
                        // is entry already exists?
96
                        if ($menu->has($property['id'])) {
97 1
                            // removes a disabled entry
98
                            if (!$enabled) {
99 1
                                $menu->remove($property['id']);
100 1
101
                                $message = sprintf('%s > %s%s (removed)', (string) $menu, $property['id'], $suffix);
102 1
                                $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
103 1
                                continue;
104
                            }
105 1
                            // merges properties
106
                            $updated = true;
107
                            $current = $menu->get($property['id'])->toArray();
108 1
                            $property = array_merge($current, $property);
109 1
110 1
                            $message = sprintf('%s > %s%s (updated)', (string) $menu, $property['id'], $suffix);
111
                            $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
112 1
                        }
113 1
                        // adds/replaces entry
114
                        if ($enabled) {
115
                            $item = (new Entry($property['id']))
116 1
                                ->setName($property['name'] ?? ucfirst($property['id']))
117 1
                                ->setUrl($property['url'] ?? '/404')
118 1
                                ->setWeight($property['weight'] ?? 0);
119 1
                            $menu->add($item);
120 1
121 1
                            if (!$updated) {
122
                                $message = sprintf('%s > %s%s', (string) $menu, $property['id'], $suffix);
123 1
                                $this->builder->getLogger()->info($message, ['progress' => [$countConfig, $totalConfig]]);
124 1
                            }
125 1
                        }
126
                    }
127
                }
128
            }
129
        }
130
131
        $this->builder->setMenus($this->menus);
132
    }
133 1
134 1
    /**
135
     * Collects pages with a menu variable.
136
     */
137
    protected function collectPages()
138
    {
139 1
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
140
            return $page->hasVariable('menu') && $page->getVariable('published');
141 1
        });
142
143
        $total = count($filteredPages);
144 1
        $count = 0;
145 1
146
        if ($total > 0) {
147 1
            $this->builder->getLogger()->debug('Creating menus from pages');
148
        }
149 1
150 1
        /** @var \Cecil\Collection\Page\Page $page */
151
        foreach ($filteredPages as $page) {
152
            $count++;
153
            $language = $page->getVariable('language') ?? $this->config->getLanguageDefault();
154 1
            /**
155 1
             * Array case.
156 1
             *
157
             * ie 1:
158
             *   menu: [main, navigation]
159
             * ie 2:
160
             *   menu:
161
             *     main:
162
             *       weight: 999
163
             */
164
            if (is_array($page->getVariable('menu'))) {
165
                foreach ($page->getVariable('menu') as $key => $value) {
166
                    $menuName = $key;
167 1
                    $property = $value;
168 1
                    $weight = null;
169 1
                    if (is_int($key)) {
170 1
                        $menuName = $value;
171 1
                        $property = null;
172 1
                    }
173 1
                    if (!is_string($menuName)) {
174 1
                        $this->builder->getLogger()->error(
175
                            sprintf(
176 1
                                'Menu\'s name of page "%s" must be a string, not "%s"',
177
                                $page->getId(),
178
                                PrintLogger::format($menuName)
179
                            ),
180
                            ['progress' => [$count, $total]]
181
                        );
182
                        continue;
183
                    }
184
                    $item = (new Entry($page->getIdWithoutLang()))
185
                        ->setName($page->getVariable('title'))
186
                        ->setUrl((new PageRenderer($this->config))->getUrl($page));
187 1
                    if (array_key_exists('weight', (array) $property)) {
188 1
                        $weight = $property['weight'];
189 1
                        $item->setWeight($property['weight']);
190 1
                    }
191 1
                    // add Menu if not exists
192 1
                    if (!$this->menus[$language]->has($menuName)) {
193
                        $this->menus[$language]->add(new Menu($menuName));
194 1
                    }
195 1
                    /** @var \Cecil\Collection\Menu\Menu $menu */
196
                    $menu = $this->menus[$language]->get($menuName);
197
                    $menu->add($item);
198 1
199 1
                    $message = sprintf('%s > %s (weight: %s)', $menuName, $page->getId(), $weight ?? 'N/A');
200
                    $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
201 1
                }
202 1
                continue;
203
            }
204 1
            /**
205
             * String case.
206
             *
207
             * ie:
208
             *   menu: main
209
             */
210
            $item = (new Entry($page->getIdWithoutLang()))
211
                ->setName($page->getVariable('title'))
212 1
                ->setUrl((new PageRenderer($this->config))->getUrl($page));
213 1
            // add Menu if not exists
214 1
            if (!$this->menus[$language]->has($page->getVariable('menu'))) {
215 1
                $this->menus[$language]->add(new Menu($page->getVariable('menu')));
216
            }
217
            /** @var \Cecil\Collection\Menu\Menu $menu */
218
            $menu = $this->menus[$language]->get($page->getVariable('menu'));
219 1
            $menu->add($item);
220 1
221
            $message = sprintf('%s > %s', $page->getVariable('menu'), $page->getId());
222 1
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
223 1
        }
224
    }
225
}
226