Passed
Push — develop ( 53798b...20a922 )
by Enea
02:15
created

AuthorizerMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

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