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