Completed
Pull Request — master (#255)
by
unknown
03:48
created

ActiveChecker::containsActive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.3332

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 6
cp 0.6667
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.3332
1
<?php
2
3
namespace JeroenNoten\LaravelAdminLte\Menu;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Http\Request;
7
use Illuminate\Contracts\Routing\UrlGenerator;
8
9
class ActiveChecker
10
{
11
    private $request;
12
13
    private $url;
14
15 32
    public function __construct(Request $request, UrlGenerator $url)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
16
    {
17 32
        $this->request = $request;
18 32
        $this->url = $url;
19 32
    }
20
21 13
    public function isActive($item)
22
    {
23 13
        if (isset($item['submenu'])) {
24 2
            return $this->containsActive($item['submenu']);
25
        }
26
27 13
        if (isset($item['active'])) {
28 3
            return $this->isExplicitActive($item['active']);
29
        }
30
31 10
        if (isset($item['href'])) {
32
            return $this->checkExactOrSub($item['href']);
33
        }
34
35
        // Support URL for backwards compatibility
36 10
        if (isset($item['url'])) {
37 9
            return $this->checkExactOrSub($item['url']);
38
        }
39
40 1
        return false;
41
    }
42
43 9
    protected function checkExactOrSub($url)
44
    {
45 9
        return $this->checkExact($url) || $this->checkSub($url);
46
    }
47
48 12
    protected function checkExact($url)
49
    {
50 12
        return $this->checkPattern($url);
51
    }
52
53 3
    protected function checkSub($url)
54
    {
55 3
        return $this->checkPattern($url.'/*');
56
    }
57
58 12
    protected function checkPattern($pattern)
59
    {
60 12
        $fullUrlPattern = $this->url->to($pattern);
61
62 12
        $fullUrl = $this->request->fullUrl();
63
64 12
        return Str::is($fullUrlPattern, $fullUrl);
65
    }
66
67 2
    protected function containsActive($items)
68
    {
69 2
        foreach ($items as $item) {
70 2
            if ($this->isActive($item)) {
71 2
                return true;
72
            }
73
        }
74
75
        return false;
76
    }
77
78 3
    private function isExplicitActive($active)
79
    {
80 3
        if (!is_array($active)) {
81
            return $active;
82
        }
83
84 3
        foreach ($active as $url) {
85 3
            if ($this->checkExact($url)) {
86 2
                return true;
87
            }
88 1
        }
89
90 1
        return false;
91
    }
92
}
93