Passed
Push — develop ( 9557ee...e4ecab )
by Enea
04:24
created

WithDeniablePermission::denialStatus()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.2098

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 5
cts 7
cp 0.7143
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 1
nop 2
crap 3.2098
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @author enea dhack <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Enea\Authorization\Operators;
13
14
use Closure;
15
use Enea\Authorization\Contracts\Grantable;
16
use Enea\Authorization\Contracts\PermissionContract;
17
use Enea\Authorization\Contracts\PermissionsOwner;
18
use Enea\Authorization\Facades\Helper;
19
use Illuminate\Support\Collection;
20
21
trait WithDeniablePermission
22
{
23
    abstract protected function isModifiable(PermissionContract $permission): bool;
24
25
    abstract protected function throwException(Grantable $grantable): void;
26
27 36
    private function getPermissions(PermissionsOwner $owner, Collection $permissions): Collection
28
    {
29 36
        return $owner->permissions()->whereKey($permissions->pluck('id'))->limit(count($permissions))->get();
30
    }
31
32 36
    private function except(Collection $granted, Collection $permissions): Collection
33
    {
34 36
        return Helper::except($permissions, $granted->pluck('secret_name')->toArray());
35
    }
36
37
    private function denialStatus(PermissionsOwner $owner, bool $denied): Closure
38
    {
39 36
        return function (PermissionContract $permission) use ($owner, $denied): void {
40 5
            if (! $this->isModifiable($permission)) {
41
                return;
42
            }
43
44 5
            $result = $owner->permissions()->updateExistingPivot($permission->getIdentificationKey(), [
45 5
                'denied' => $denied
46
            ]);
47
48 5
            if (! $this->isSuccessful($result)) {
49
                $this->throwException($permission);
50
            }
51 36
        };
52
    }
53
54 5
    private function isSuccessful(int $results): bool
55
    {
56 5
        return $results > 0;
57
    }
58
}
59