Passed
Branch develop (f66584)
by Enea
02:08
created

Granter::addTo()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 9.4285
c 0
b 0
f 0
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