Passed
Push — chore/code ( eb65af )
by Arnaud
05:25
created

Create::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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