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

Granter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 7
dl 0
loc 37
ccs 18
cts 19
cp 0.9474
rs 10

5 Methods

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