Completed
Push — develop ( 969b3c...da2fc5 )
by Enea
01:58
created

Granter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A saveIn() 0 6 2
A grantTo() 0 4 1
A dispatchGrantedEvent() 0 3 1
A permissions() 0 4 1
A roles() 0 4 1
A addTo() 0 4 1
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\Granted;
16
use Enea\Authorization\Exceptions\AuthorizationNotGrantedException;
17
use Exception;
18
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
19
use Illuminate\Support\Collection;
20
21
class Granter extends Operator
22
{
23 30
    public function permissions(PermissionsOwner $owner, Collection $permissions): void
24
    {
25 30
        $this->grantTo($owner->permissions())($permissions);
26 29
        $this->dispatchGrantedEvent($owner, $permissions);
27 29
    }
28
29 24
    public function roles(RolesOwner $owner, Collection $roles): void
30
    {
31 24
        $this->grantTo($owner->roles())($roles);
32 23
        $this->dispatchGrantedEvent($owner, $roles);
33 23
    }
34
35
    private function grantTo(BelongsToMany $repository): Closure
36
    {
37 32
        return function (Collection $grantableCollection) use ($repository): void {
38 32
            $grantableCollection->each($this->addTo($repository));
39 32
        };
40
    }
41
42
    protected function addTo(BelongsToMany $authorizations): Closure
43
    {
44 32
        return function (Grantable $grantable) use ($authorizations): void {
45 32
            $this->saveIn($grantable, $authorizations);
46 32
        };
47
    }
48
49 32
    private function saveIn(Grantable $grantable, BelongsToMany $authorizations): void
50
    {
51
        try {
52 32
            $authorizations->save($this->castToModel($grantable));
53 2
        } catch (Exception $exception) {
54 2
            throw new AuthorizationNotGrantedException($grantable, $exception);
55
        }
56 30
    }
57
58 30
    private function dispatchGrantedEvent(GrantableOwner $owner, Collection $grantableCollection): void
59
    {
60 30
        $this->dispatchEvent(new Granted($owner, $grantableCollection));
61 30
    }
62
}
63