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

PermissionEvaluator::getDeniedPermissions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 2
crap 1
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\Drivers\Database;
13
14
use Enea\Authorization\Contracts\PermissionsOwner;
15
use Enea\Authorization\Contracts\RolesOwner;
16
use Illuminate\Support\Collection;
17
18
class PermissionEvaluator extends Evaluator
19
{
20 7
    public function evaluate(PermissionsOwner $owner, array $permissions): bool
21
    {
22 7
        $denied = $this->getDeniedPermissions($owner, $permissions);
23
24 7
        if ($denied->count() === count($permissions)) {
25 3
            return false;
26
        }
27
28 7
        $permissions = $this->clean($permissions, $denied);
29 7
        return $this->searchInRoles($owner, $permissions) || $this->has($owner->permissions()->getQuery())($permissions);
30
    }
31
32 7
    private function getDeniedPermissions(PermissionsOwner $owner, array $permissions): Collection
33
    {
34 7
        return $owner->permissions()->where('denied', true)->whereIn('secret_name', $permissions)->limit(count($permissions))->get();
35
    }
36
37 7
    private function clean(array $permissions, Collection $denied): array
38
    {
39 7
        $names = $denied->pluck('secret_name')->toArray();
40 7
        return array_filter($permissions, function (string $secret) use ($names): bool {
41 7
            return ! in_array($secret, $names);
42 7
        });
43
    }
44
45 7
    private function searchInRoles(PermissionsOwner $owner, array $permissions): bool
46
    {
47 7
        return $owner instanceof RolesOwner ? $this->hasPermissions($owner, $permissions) : false;
48
    }
49
50 7
    private function hasPermissions(RolesOwner $owner, array $permissions): bool
51
    {
52 7
        return $owner->roles()->limit(1)->whereHas('permissions', $this->same($permissions))->exists();
53
    }
54
}
55