Insertable::insertBefore()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace JumpGate\Menu\Traits;
4
5
/**
6
 * Class Insertable
7
 *
8
 * @package JumpGate\Menu\Traits
9
 *
10
 * @property \JumpGate\Menu\Menu $menu
11
 */
12
trait Insertable
13
{
14
    /**
15
     * Let the add method know not to append this item as it was spliced into the array.
16
     *
17
     * @var bool
18
     */
19
    public $insert = false;
20
21
    /**
22
     * Insert this item after another item in the menu
23
     *
24
     * @param $slug
25
     */
26
    public function insertAfter($slug)
27
    {
28
        $this->insertObject($slug, true);
29
    }
30
31
    /**
32
     * Insert this item before another item in the menu
33
     *
34
     * @param $slug
35
     */
36
    public function insertBefore($slug)
37
    {
38
        $this->insertObject($slug);
39
    }
40
41
    /**
42
     * @param $slug
43
     * @param $after
44
     */
45
    private function insertObject($slug, $after = false)
46
    {
47
        $this->insert = true;
48
49
        foreach ($this->menu->links as $linkKey => $link) {
50
            if ($link->isDropdown()) {
51
                foreach ($link->links as $subLinkKey => $subLink) {
52
                    if ($subLink->slug == $slug) {
53
                        if ($after) {
54
                            $link->links->splice($subLinkKey + 1, 0, [$this]);
55
                        } else {
56
                            $link->links->splice($subLinkKey, 0, [$this]);
57
                        }
58
                    }
59
                }
60
            } else {
61
                if ($link->slug == $slug) {
62
                    if ($after) {
63
                        $this->menu->links->splice($linkKey + 1, 0, [$this]);
64
                    } else {
65
                        $this->menu->links->splice($linkKey, 0, [$this]);
66
                    }
67
                }
68
            }
69
        }
70
    }
71
}
72