Completed
Push — develop ( 20a922...5bb600 )
by Enea
05:08 queued 03:13
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
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