Completed
Push — master ( 0637c9...3619a3 )
by Jeroen
06:18
created

ActiveChecker::checkExactOrSub()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 2
eloc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace JeroenNoten\LaravelAdminLte\Menu;
4
5
use Illuminate\Contracts\Routing\UrlGenerator;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Str;
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 30
    public function isActive($item)
22
    {
23 30
        if (isset($item['active'])) {
24 3
            return $this->isExplicitActive($item['active']);
25
        }
26
27 27
        if (isset($item['submenu'])) {
28 8
            return $this->containsActive($item['submenu']);
29
        }
30
31 24
        if (isset($item['href'])) {
32 14
            return $this->checkExactOrSub($item['href']);
33
        }
34
35
        // Support URL for backwards compatibility
36 13
        if (isset($item['url'])) {
37 12
            return $this->checkExactOrSub($item['url']);
38
        }
39
40 1
        return false;
41
    }
42
43 23
    protected function checkExactOrSub($url) {
44 23
        return $this->checkExact($url) || $this->checkSub($url);
45
    }
46
47 26
    protected function checkExact($url)
48
    {
49 26
        return $this->checkPattern($url);
50
    }
51
52 11
    protected function checkSub($url)
53
    {
54 11
        return $this->checkPattern($url.'/*');
55
    }
56
57 26
    protected function checkPattern($pattern)
58
    {
59 26
        $fullUrlPattern = $this->url->to($pattern);
60
61 26
        $fullUrl = $this->request->fullUrl();
62
63 26
        return Str::is($fullUrlPattern, $fullUrl);
64
    }
65
66 8
    protected function containsActive($items)
67
    {
68 8
        foreach ($items as $item) {
69 5
            if ($this->isActive($item)) {
70 3
                return true;
71
            }
72 5
        }
73
74 5
        return false;
75
    }
76
77 3
    private function isExplicitActive($active)
78
    {
79 3
        foreach ($active as $url) {
80 3
            if ($this->checkExact($url)) {
81 2
                return true;
82
            }
83 1
        }
84
85 1
        return false;
86
    }
87
}
88