Completed
Push — develop ( c127f1...97f65e )
by Enea
03:21
created

PermissionRepository::permissions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2.032
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\Cache\Repositories;
13
14
use Enea\Authorization\Contracts\Grantable;
15
use Enea\Authorization\Contracts\PermissionsOwner;
16
use Enea\Authorization\Contracts\RolesOwner;
17
use Illuminate\Support\Collection;
18
19
class PermissionRepository extends Repository
20
{
21 3
    protected function getSuffix(): string
22
    {
23 3
        return 'permissions';
24
    }
25
26
    public function toCollection(PermissionsOwner $owner): Collection
27
    {
28 3
        return $this->remember($owner, function () use ($owner) {
29 3
            return $this->permissions($owner);
30 3
        });
31
    }
32
33 3
    private function permissions(PermissionsOwner $owner): Collection
34
    {
35 3
        $permissions = $owner->getPermissionModels();
36
37 3
        if ($owner instanceof RolesOwner) {
38 3
            return $this->permissionsFromRole($owner)->merge($permissions)->map($this->parse());
39
        }
40
41
        return $permissions->map($this->parse());
42
    }
43
44
    private function permissionsFromRole(RolesOwner $owner): Collection
45
    {
46 3
        return $this->extractPermissions($owner)->unique(function (Grantable $grantable) {
47 1
            return $grantable->getIdentificationKey();
48 3
        });
49
    }
50
51
    private function extractPermissions(RolesOwner $owner): Collection
52
    {
53 3
        return $owner->roles()->with('permissions')->get()->map(function (PermissionsOwner $owner): Collection {
54 1
            return $owner->getPermissionModels();
55 3
        })->collapse();
56
    }
57
}
58