Completed
Push — develop ( 20a922...5bb600 )
by Enea
05:08 queued 03:13
created

AuthorizerMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isAuthorizedRequestFor() 0 4 2
A handle() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Created on 10/03/18 by enea dhack.
7
 */
8
9
namespace Enea\Authorization\Middleware;
10
11
use Closure;
12
use Enea\Authorization\Authorizer;
13
use Enea\Authorization\Contracts\GrantableOwner;
14
use Enea\Authorization\Events\UnauthorizedOwner;
15
use Enea\Authorization\Exceptions\UnauthorizedOwnerException;
16
use Illuminate\Database\Eloquent\Model;
17
use Illuminate\Events\Dispatcher;
18
use Illuminate\Http\Request;
19
20
abstract class AuthorizerMiddleware
21
{
22
    protected $authorizer;
23
24
    private $event;
25
26 8
    public function __construct(Authorizer $authorizer, Dispatcher $event)
27
    {
28 8
        $this->authorizer = $authorizer;
29 8
        $this->event = $event;
30 8
    }
31
32
    abstract protected function authorized(GrantableOwner $owner, array $grantables): bool;
33
34 8
    public function handle(Request $request, Closure $next, string ...$grantables)
35
    {
36 8
        $authenticated = $request->user();
37
38 8
        if ($this->isAuthorizedRequestFor($authenticated)($grantables)) {
39 4
            return $next($request);
40
        }
41
42 4
        $this->event->dispatch(new UnauthorizedOwner($authenticated, $grantables));
43
44 4
        throw new UnauthorizedOwnerException($authenticated);
45
    }
46
47
    private function isAuthorizedRequestFor(Model $authenticated): Closure
48
    {
49 8
        return function (array $grantables) use ($authenticated): bool {
50 8
            return $authenticated instanceof GrantableOwner && $this->authorized($authenticated, $grantables);
51 8
        };
52
    }
53
}
54