Passed
Push — master ( c62529...5628da )
by Florian
03:24
created

GateFilter::isAllowed()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 6
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 19
ccs 7
cts 7
cp 1
crap 5
rs 9.6111
1
<?php
2
3
namespace JeroenNoten\LaravelAdminLte\Menu\Filters;
4
5
use Illuminate\Contracts\Auth\Access\Gate;
6
7
class GateFilter implements FilterInterface
8
{
9
    /**
10
     * The Laravel gate instance, used to check for permissions.
11
     *
12
     * @var Gate
13
     */
14
    protected $gate;
15
16
    /**
17
     * Constructor.
18
     *
19
     * @param Gate $gate
20
     */
21 44
    public function __construct(Gate $gate)
22
    {
23 44
        $this->gate = $gate;
24 44
    }
25
26
    /**
27
     * Transforms a menu item. Add the restricted property to a menu item
28
     * when situable.
29
     *
30
     * @param array $item A menu item
31
     * @return array The transformed menu item
32
     */
33 44
    public function transform($item)
34
    {
35
        // Set a special attribute when item is not allowed. Items with this
36
        // attribute will be filtered out of the menu.
37
38 44
        if (! $this->isAllowed($item)) {
39 4
            $item['restricted'] = true;
40
        }
41
42 44
        return $item;
43
    }
44
45
    /**
46
     * Check if a menu item is allowed for the current user.
47
     *
48
     * @param array $item A menu item
49
     * @return bool
50
     */
51 44
    protected function isAllowed($item)
52
    {
53
        // Check if there are any permission defined for the item.
54
55 44
        if (empty($item['can'])) {
56 41
            return true;
57
        }
58
59
        // Read the extra arguments (a db model instance can be used).
60
61 5
        $args = isset($item['model']) ? $item['model'] : [];
62
63
        // Check if the current user can perform the configured permissions.
64
65 5
        if (is_string($item['can']) || is_array($item['can'])) {
66 4
            return $this->gate->any($item['can'], $args);
67
        }
68
69 1
        return true;
70
    }
71
}
72