AuthMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 5
dl 0
loc 46
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 12 4
1
<?php
2
3
namespace App\Middleware;
4
5
use Awurth\Slim\Helper\Exception\AccessDeniedException;
6
use Cartalyst\Sentinel\Sentinel;
7
use Slim\Flash\Messages;
8
use Slim\Http\Request;
9
use Slim\Http\Response;
10
use Slim\Router;
11
12
class AuthMiddleware implements MiddlewareInterface
13
{
14
    /**
15
     * @var Messages
16
     */
17
    protected $flash;
18
19
    /**
20
     * @var string
21
     */
22
    protected $role;
23
24
    /**
25
     * @var Router
26
     */
27
    protected $router;
28
29
    /**
30
     * @var Sentinel
31
     */
32
    protected $sentinel;
33
34
    public function __construct(Router $router, Messages $flash, Sentinel $sentinel, $role = null)
35
    {
36
        $this->router = $router;
37
        $this->flash = $flash;
38
        $this->sentinel = $sentinel;
39
        $this->role = $role;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function __invoke(Request $request, Response $response, callable $next)
46
    {
47
        if (!$this->sentinel->check()) {
48
            $this->flash->addMessage('error', 'You must be logged in to access this page!');
49
50
            return $response->withRedirect($this->router->pathFor('login'));
51
        } elseif ($this->role && !$this->sentinel->inRole($this->role)) {
52
            throw new AccessDeniedException($request, $response);
53
        }
54
55
        return $next($request, $response);
56
    }
57
}
58