Passed
Push — analysis-NAZOOp ( 2f2415 )
by Arnaud
04:52 queued 10s
created

MenusCreate::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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