RoleMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 73.91%

Importance

Changes 8
Bugs 0 Features 2
Metric Value
wmc 8
c 8
b 0
f 2
lcom 1
cbo 3
dl 0
loc 72
ccs 17
cts 23
cp 0.7391
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C handle() 0 34 7
1
<?php
2
3
/**
4
 * @package     Dashboard
5
 * @author      Ian Olson <[email protected]>
6
 * @license     MIT
7
 * @copyright   2015, Laraflock
8
 * @link        https://github.com/laraflock
9
 */
10
11
namespace Laraflock\Dashboard\Middleware;
12
13
use Closure;
14
use Illuminate\Http\Request;
15
use Laracasts\Flash\Flash;
16
use Laraflock\Dashboard\Repositories\Auth\AuthRepositoryInterface as Auth;
17
use Laraflock\Dashboard\Repositories\Role\RoleRepositoryInterface as Role;
18
19
class RoleMiddleware
20
{
21
    /**
22
     * Auth interface.
23
     *
24
     * @var Auth
25
     */
26
    protected $auth;
27
28
    /**
29
     * Role interface.
30
     *
31
     * @var Role
32
     */
33
    protected $role;
34
35
    /**
36
     * The constructor.
37
     *
38
     * @param Auth $auth
39
     * @param Role $role
40
     */
41 2
    public function __construct(Auth $auth, Role $role)
42
    {
43 2
        $this->auth = $auth;
44 2
        $this->role = $role;
45 2
    }
46
47
    /**
48
     * Check if user belongs to the specified role.
49
     *
50
     * @param Request      $request
51
     * @param Closure      $next
52
     * @param string|array $roles
53
     *
54
     * @return \Illuminate\Http\RedirectResponse
55
     */
56 1
    public function handle(Request $request, Closure $next, $roles)
57
    {
58 1
        $accessDenied = true;
59
60 1
        if (!$user = $this->auth->getActiveUser()) {
61
            Flash::error(trans('dashboard::dashboard.flash.access_denied'));
62
63
            return redirect()->route('auth.login');
64
        }
65
66 1
        if (!is_array($roles)) {
67 1
            $roles = [$roles];
68 1
        }
69
70 1
        foreach ($roles as $role) {
71
72 1
            if (!$role = $this->role->getBySlug($role)) {
73
                continue;
74
            }
75
76 1
            if ($user->inRole($role)) {
77
                $accessDenied = false;
78
            }
79 1
        }
80
81 1
        if ($accessDenied) {
82 1
            Flash::error(trans('dashboard::dashboard.flash.access_denied'));
83
84
            // Redirect back to the previous page where request was made.
85 1
            return redirect()->back();
86
        }
87
88
        return $next($request);
89
    }
90
}