PermissionEvaluator::evaluate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
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