Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.77% covered (success)
96.77%
120 / 124
93.33% covered (success)
93.33%
14 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Menu
96.77% covered (success)
96.77%
120 / 124
93.33% covered (success)
93.33%
14 / 15
45
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 rewind
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 current
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 next
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 valid
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 html
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 compileHtml
91.49% covered (success)
91.49%
43 / 47
0.00% covered (danger)
0.00%
0 / 1
12.09
 anchorAttributes
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 escape
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 makeTree
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 branch
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 expand
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 childRows
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 nodeRows
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Finder;
6
7use Cosray\Cms;
8use Cosray\Context;
9use Cosray\Exception\RuntimeException;
10use Cosray\Markup;
11use Iterator;
12use Override;
13
14/** @implements Iterator<string, MenuItem> */
15class Menu implements Iterator
16{
17    /** The `order` values a `children` item may configure. */
18    public const array CHILD_ORDERS = ['title', 'created', 'created desc', 'changed desc', 'manual'];
19
20    /** @var array<string, array<string, mixed>> */
21    protected array $items;
22    protected int $pointer = 0;
23
24    /**
25     * `$expand` resolves dynamic `children` items into node entries at
26     * read time; the panel editor turns it off to show the items as
27     * stored. Expansion needs the `$cms` finder entry point — without
28     * one, `children` items render as nothing.
29     *
30     * `$hidden` includes hidden items; the panel editor asks for them so
31     * it can show what the site does not.
32     */
33    public function __construct(
34        protected readonly Context $context,
35        string $menu,
36        protected readonly ?Cms $cms = null,
37        bool $expand = true,
38        bool $hidden = false,
39    ) {
40        $rows = $context->db->menus->get(['menu' => $menu])->all();
41
42        if (!$hidden) {
43            // Dropping the row is enough to drop its subtree: `makeTree` nests
44            // by parent, so children of a hidden item find no group to join.
45            $rows = array_values(array_filter(
46                $rows,
47                static fn(array $row): bool => !$row['hidden'],
48            ));
49        }
50
51        $this->items = $this->makeTree($rows);
52
53        // An existing menu without items iterates nothing and renders as
54        // an empty string; only an unknown menu is an error.
55        if (
56            count($this->items) === 0
57            && !$context->db->menus->exists(['menu' => $menu])->first()
58        ) {
59            throw new RuntimeException("Menu '{$menu}' not found");
60        }
61
62        if ($expand) {
63            $this->items = $this->expand($this->items);
64        }
65    }
66
67    #[Override]
68    public function rewind(): void
69    {
70        reset($this->items);
71    }
72
73    #[Override]
74    public function current(): MenuItem
75    {
76        $item = current($this->items);
77
78        return $item !== false
79            ? new MenuItem($this->context, $item)
80            : throw new RuntimeException('The menu iterator is past its end');
81    }
82
83    #[Override]
84    public function key(): string
85    {
86        return key($this->items) ?? throw new RuntimeException('The menu iterator is past its end');
87    }
88
89    #[Override]
90    public function next(): void
91    {
92        next($this->items);
93    }
94
95    #[Override]
96    public function valid(): bool
97    {
98        return key($this->items) !== null;
99    }
100
101    public function html(string $class = '', string $tag = 'nav'): Markup
102    {
103        return new Markup($this->compileHtml($this, $class, $tag));
104    }
105
106    protected function compileHtml(
107        Iterator $items,
108        string $class = '',
109        string $tag = 'nav',
110    ): string {
111        $out = '';
112        $level = 1;
113
114        foreach ($items as $item) {
115            $level = $item->level();
116            $itemClass = $item->class();
117            $image = $item->image() ?: '';
118
119            if ($image) {
120                $image = sprintf(
121                    '<div class="nav-image"><img src="%s" alt="Navigation Icon"/></div>',
122                    $this->escape($image),
123                );
124            }
125
126            $submenu = $this->compileHtml($item->children(), tag: '');
127
128            if ($submenu) {
129                $submenu = sprintf('<div class="nav-submenu">%s</div>', $submenu);
130            }
131
132            $content = sprintf(
133                '%s<div class="nav-label"><span>%s</span></div>%s',
134                $image,
135                $this->escape($item->title()),
136                $submenu,
137            );
138            $href = $item->href();
139
140            if ($href !== null) {
141                $content = sprintf('<a%s>%s</a>', $this->anchorAttributes($item, $href), $content);
142            }
143
144            $out .= sprintf(
145                '<li class="nav-level-%s%s%s">%s</li>',
146                (string) $level,
147                $item->hasChildren() ? ' nav-has-children' : '',
148                $itemClass ? ' ' . $this->escape($itemClass) : '',
149                $content,
150            );
151        }
152
153        if ($out === '') {
154            return '';
155        }
156
157        if ($tag) {
158            return sprintf(
159                '<%s%s><ul class="nav-level-%s">%s</ul></%s>',
160                $tag,
161                $class ? sprintf(' class="%s"', $this->escape($class)) : '',
162                $level,
163                $out,
164                $tag,
165            );
166        }
167
168        return sprintf(
169            '<ul class="%snav-level-%s">%s</ul>',
170            $class ? $this->escape($class) . ' ' : '',
171            $level,
172            $out,
173        );
174    }
175
176    protected function anchorAttributes(MenuItem $item, string $href): string
177    {
178        $attributes = sprintf(' href="%s"', $this->escape($href));
179        $target = $item->target();
180
181        if ($target !== null) {
182            $attributes .= sprintf(' target="%s"', $this->escape($target));
183
184            if ($target === '_blank') {
185                $attributes .= ' rel="noopener"';
186            }
187        }
188
189        return $attributes;
190    }
191
192    protected function escape(string $value): string
193    {
194        return htmlspecialchars($value, ENT_QUOTES);
195    }
196
197    /**
198     * Nests the sorted rows by their parent column. Splitting the CTE's
199     * dotted path would duplicate items whose ids contain a dot.
200     *
201     * @param list<array<string, mixed>> $items
202     * @return array<string, array<string, mixed>>
203     */
204    protected function makeTree(array $items): array
205    {
206        $grouped = [];
207
208        foreach ($items as $item) {
209            $grouped[$item['parent'] ?? ''][$item['item']] = $item;
210        }
211
212        return $this->branch($grouped, '');
213    }
214
215    /**
216     * @param array<array-key, array<array-key, array<string, mixed>>> $grouped
217     * @return array<string, array<string, mixed>>
218     */
219    private function branch(array $grouped, string $parent): array
220    {
221        $tree = [];
222
223        foreach ($grouped[$parent] ?? [] as $id => $item) {
224            $item['children'] = $this->branch($grouped, $id);
225            $tree[$id] = $item;
226        }
227
228        return $tree;
229    }
230
231    /**
232     * Replaces every `children` item in place with the linked node's
233     * published, visible children, `levels` deep and in the configured
234     * order. The entries are synthesized as `node` rows carrying their
235     * resolved title and path for the current locale, so rendering
236     * treats them exactly like hand-placed node items.
237     *
238     * @param array<string, array<string, mixed>> $items
239     * @return array<string, array<string, mixed>>
240     */
241    protected function expand(array $items): array
242    {
243        $result = [];
244
245        foreach ($items as $id => $item) {
246            $data = json_decode((string) $item['data'], true);
247            $data = is_array($data) ? $data : [];
248
249            if (($data['type'] ?? '') === 'children') {
250                $result += $this->childRows($data, (int) $item['level']);
251
252                continue;
253            }
254
255            $item['children'] = $this->expand($item['children']);
256            $result[$id] = $item;
257        }
258
259        return $result;
260    }
261
262    /**
263     * @param array<mixed> $data
264     * @return array<string, array<string, mixed>>
265     */
266    private function childRows(array $data, int $level): array
267    {
268        $uid = $data['node'] ?? null;
269
270        if ($this->cms === null || !is_string($uid) || $uid === '') {
271            return [];
272        }
273
274        $order = $data['order'] ?? '';
275        $order = in_array($order, self::CHILD_ORDERS, true) ? $order : 'title';
276
277        return $this->nodeRows($uid, $level, max(1, (int) ($data['levels'] ?? 1)), $order);
278    }
279
280    /** @return array<string, array<string, mixed>> */
281    private function nodeRows(string $uid, int $level, int $depth, string $order): array
282    {
283        assert($this->cms !== null, 'childRows guards the finder entry point');
284        $locale = $this->context->locale()->id;
285        $rows = [];
286
287        // The uid tie-break keeps equal sort keys deterministic; the manual
288        // order brings its own, and falls back to titles for a parent whose
289        // children nobody arranged.
290        $children = $this->cms->nodes()->childrenOf($uid);
291        $children = $order === 'manual'
292            ? $children->order(new Order(SortField::position()))
293            : $children->order($order, 'id');
294
295        foreach ($children as $node) {
296            $childUid = (string) $node->meta->uid;
297            $key = 'children:' . $childUid;
298
299            $rows[$key] = [
300                'item' => $key,
301                'parent' => null,
302                'level' => $level,
303                'data' => json_encode([
304                    'type' => 'node',
305                    'node' => $childUid,
306                    'title' => [$locale => $node->title()],
307                    'path' => [$locale => $node->path()],
308                ]),
309                'children' => $depth > 1
310                    ? $this->nodeRows($childUid, $level + 1, $depth - 1, $order)
311                    : [],
312            ];
313        }
314
315        return $rows;
316    }
317}