AuthMiddleware::execute()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
rs 9.8666
cc 3
nc 3
nop 2
1
<?php
2
3
4
namespace hiapi\middlewares;
5
6
use hiapi\exceptions\InsufficientPermissionsException;
7
use hiapi\exceptions\NotAuthenticatedException;
8
use League\Tactician\Middleware;
9
use yii\web\User;
10
11
/**
12
 * Class AuthMiddleware
13
 *
14
 * @author Dmytro Naumenko <[email protected]>
15
 */
16
class AuthMiddleware implements Middleware
17
{
18
    /**
19
     * @var string
20
     */
21
    private $permission;
22
    /**
23
     * @var User
24
     */
25
    private $user;
26
27
    public function __construct(string $permission, User $user)
28
    {
29
        $this->permission = $permission;
30
        $this->user = $user;
31
    }
32
33
    /**
34
     * @param object $command
35
     * @param callable $next
36
     *
37
     * @return mixed
38
     * @throws InsufficientPermissionsException
39
     * @throws NotAuthenticatedException
40
     */
41
    public function execute($command, callable $next)
42
    {
43
        if ($this->user->getId() === null) {
44
            throw new NotAuthenticatedException();
45
        }
46
47
        if (!$this->user->can($this->permission)) {
48
            throw new InsufficientPermissionsException($this->permission);
49
        }
50
51
        return $next($command);
52
    }
53
}
54