Completed
Push — develop ( 0bdcf1...3b506c )
by Enea
09:31 queued 08:05
created

Revoker::permission()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
/**
3
 * Created on 12/02/18 by enea dhack.
4
 */
5
6
namespace Enea\Authorization\Operators;
7
8
use Closure;
9
use Enea\Authorization\Contracts\{
10
    Grantable, GrantableOwner, PermissionsOwner, RolesOwner
11
};
12
use Enea\Authorization\Events\Revoked;
13
use Enea\Authorization\Exceptions\AuthorizationNotRevokedException;
14
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
15
use Illuminate\Support\Collection;
16
17
class Revoker extends Operator
18
{
19 6
    public function permissions(PermissionsOwner $owner, Collection $permissions): void
20
    {
21 6
        $this->revokeTo($owner->permissions())($permissions);
22 6
        $this->dispatchRevokedEvent($owner, $permissions);
23 6
    }
24
25 3
    public function roles(RolesOwner $owner, Collection $roles): void
26
    {
27 3
        $this->revokeTo($owner->roles())($roles);
28 3
        $this->dispatchRevokedEvent($owner, $roles);
29 3
    }
30
31
    private function revokeTo(BelongsToMany $repository): Closure
32
    {
33 9
        return function (Collection $grantableCollection) use ($repository): void {
34 9
            $grantableCollection->each($this->removeFrom($repository));
35 9
        };
36
    }
37
38
    private function removeFrom(BelongsToMany $authorizations): Closure
39
    {
40 9
        return function (Grantable $grantable) use ($authorizations): void {
41 9
            $result = $authorizations->detach($this->castToModel($grantable));
42
43 9
            if (! $this->isSuccessful($result)) {
44
                throw new AuthorizationNotRevokedException($grantable);
45
            }
46 9
        };
47
    }
48
49 9
    private function isSuccessful(int $results): bool
50
    {
51 9
        return $results > 0;
52
    }
53
54 9
    private function dispatchRevokedEvent(GrantableOwner $owner, Collection $grantableCollection): void
55
    {
56 9
        $this->dispatchEvent(new Revoked($owner, $grantableCollection));
57 9
    }
58
}
59