Completed
Pull Request — master (#131)
by
unknown
09:57 queued 08:54
created

ActiveChecker::containsActive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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