Completed
Pull Request — master (#547)
by
unknown
02:47
created

ActiveChecker::isActive()   B

Complexity

Conditions 9
Paths 5

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 9

Importance

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