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

PermissionRepository::permissionsFromRole()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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