Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.66% covered (warning)
89.66%
26 / 29
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
MenuBuilder
89.66% covered (warning)
89.66%
26 / 29
66.67% covered (warning)
66.67%
2 / 3
12.16
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRoot
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addLeaf
88.89% covered (warning)
88.89%
24 / 27
0.00% covered (danger)
0.00%
0 / 1
10.14
1<?php
2namespace Apie\Common\MenuStructure;
3
4use Apie\Core\Lists\StringList;
5
6class MenuBuilder
7{
8    private MenuNode $root;
9
10    public function __construct(private readonly string $prefix = '')
11    {
12        $this->root = new MenuNode(rtrim($this->prefix, '.-'), '');
13    }
14
15    public function getRoot(): MenuNode
16    {
17        return $this->root;
18    }
19
20    public function addLeaf(string|StringList $tag, MenuNode $leaf): self
21    {
22        if (is_string($tag)) {
23            $tag = new StringList([$tag]);
24        }
25        $parent = null;
26        $current = $this->root;
27        foreach ($tag as $part) {
28            $parent = $current;
29            if (!isset($current->children[$part])) {
30                $children = $current->children;
31                $children[$part] = new MenuNode($this->prefix . $part, '');
32                $current->children = $children;
33            }
34            $current = $current->children[$part];
35            $lastKey = $part;
36        }
37        if ($parent === null) {
38            $this->root = $leaf;
39            return $this;
40        }
41        if ($current->children->count()) {
42            $current->name = $leaf->name;
43            $current->route = $leaf->route;
44            $current->icon = $leaf->icon;
45        } elseif ($current->name && $current->id !== $leaf->id) {
46            for ($i = 0; $i < 1000; $i++) {
47                if (!isset($parent->children[$lastKey . '-' . $i])) {
48                    $parent->children[$lastKey . '-' . $i] = $leaf;
49                    return $this;
50                }
51            }
52            throw new \LogicException(sprintf('There is already a leaf with id %s', $current->id));
53        } else {
54            $parent->children[$lastKey] = $leaf;
55        }
56
57        return $this;
58    }
59}