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

AuthorizerMiddleware::isAuthorizedRequestFor()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
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