Completed
Branch master (928280)
by Alexis
02:27
created

AuthMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
lcom 0
cbo 5
dl 0
loc 54
rs 10
c 1
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 App\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
    /**
35
     * Constructor.
36
     *
37
     * @param Router   $router
38
     * @param Messages $flash
39
     * @param Sentinel $sentinel
40
     * @param string   $role
41
     */
42
    public function __construct(Router $router, Messages $flash, Sentinel $sentinel, $role = null)
43
    {
44
        $this->router = $router;
45
        $this->flash = $flash;
46
        $this->sentinel = $sentinel;
47
        $this->role = $role;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function __invoke(Request $request, Response $response, callable $next)
54
    {
55
        if (!$this->sentinel->check()) {
56
            $this->flash->addMessage('error', 'You must be logged in to access this page!');
57
58
            return $response->withRedirect($this->router->pathFor('login'));
59
        } elseif ($this->role && !$this->sentinel->inRole($this->role)) {
60
            throw new AccessDeniedException($request, $response);
61
        }
62
63
        return $next($request, $response);
64
    }
65
}
66