Role::findByName()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 8
c 2
b 1
f 0
nc 2
nop 2
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Maklad\Permission\Models;
4
5
use Jenssegers\Mongodb\Eloquent\Model;
6
use Jenssegers\Mongodb\Relations\BelongsToMany;
7
use Maklad\Permission\Contracts\RoleInterface;
8
use Maklad\Permission\Exceptions\GuardDoesNotMatch;
9
use Maklad\Permission\Exceptions\RoleAlreadyExists;
10
use Maklad\Permission\Exceptions\RoleDoesNotExist;
11
use Maklad\Permission\Guard;
12
use Maklad\Permission\Helpers;
13
use Maklad\Permission\Traits\HasPermissions;
14
use Maklad\Permission\Traits\RefreshesPermissionCache;
15
use ReflectionException;
16
17
/**
18
 * Class Role
19
 * @package Maklad\Permission\Models
20
 */
21
class Role extends Model implements RoleInterface
22
{
23
    use HasPermissions;
0 ignored issues
show
introduced by
The trait Maklad\Permission\Traits\HasPermissions requires some properties which are not provided by Maklad\Permission\Models\Role: $permissions, $roles, $forceDeleting, $guard_name
Loading history...
24
    use RefreshesPermissionCache;
25
26
    public $guarded = ['id'];
27
    protected $helpers;
28
29
    /**
30
     * Role constructor.
31
     *
32
     * @param array $attributes
33
     *
34
     * @throws \ReflectionException
35 123
     */
36
    public function __construct(array $attributes = [])
37 123
    {
38
        $attributes['guard_name'] = $attributes['guard_name'] ?? (new Guard())->getDefaultName(static::class);
39 123
40
        parent::__construct($attributes);
41 123
42
        $this->helpers = new Helpers();
43 123
44 123
        $this->setTable(config('permission.collection_names.roles'));
45
    }
46
47
    /**
48
     * @param array $attributes
49
     *
50
     * @return $this|Model
51
     * @throws RoleAlreadyExists
52
     * @internal param array $attributes§
53
     *
54
     * @throws \ReflectionException
55 123
     */
56
    public static function create(array $attributes = [])
57 123
    {
58 123
        $attributes['guard_name'] = $attributes['guard_name'] ?? (new Guard())->getDefaultName(static::class);
59
        $helpers = new Helpers();
60 123
61 1
        if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) {
62 1
            $name = (string)$attributes['name'];
63 1
            $guardName = (string)$attributes['guard_name'];
64
            throw new RoleAlreadyExists($helpers->getRoleAlreadyExistsMessage($name, $guardName));
65
        }
66 123
67
        return $helpers->checkVersion() ? parent::create($attributes) : static::query()->create($attributes);
0 ignored issues
show
Bug introduced by
The method create() does not exist on Jenssegers\Mongodb\Eloquent\Model. Did you maybe mean created()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
        return $helpers->checkVersion() ? parent::/** @scrutinizer ignore-call */ create($attributes) : static::query()->create($attributes);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68
    }
69
70 123
    /**
71
     * Find or create role by its name (and optionally guardName).
72
     *
73
     * @param string $name
74
     * @param string|null $guardName
75
     *
76
     * @return RoleInterface
77
     * @throws \Maklad\Permission\Exceptions\RoleAlreadyExists
78
     * @throws \ReflectionException
79
     */
80
    public static function findOrCreate(string $name, $guardName = null): RoleInterface
81
    {
82
        $guardName = $guardName ?? (new Guard())->getDefaultName(static::class);
83 1
84
        $role = static::where('name', $name)
85 1
            ->where('guard_name', $guardName)
86
            ->first();
87 1
88 1
        if (!$role) {
89 1
            $role = static::create(['name' => $name, 'guard_name' => $guardName]);
90
        }
91 1
92 1
        return $role;
93
    }
94
95 1
    /**
96
     * Find a role by its name and guard name.
97
     *
98
     * @param string $name
99
     * @param string|null $guardName
100
     *
101
     * @return RoleInterface
102
     * @throws RoleDoesNotExist
103
     * @throws \ReflectionException
104
     */
105
    public static function findByName(string $name, $guardName = null): RoleInterface
106
    {
107
        $guardName = $guardName ?? (new Guard())->getDefaultName(static::class);
108 49
109
        $role = static::where('name', $name)
110 49
            ->where('guard_name', $guardName)
111
            ->first();
112 49
113 49
        if (!$role) {
114 49
            $helpers = new Helpers();
115
            throw new RoleDoesNotExist($helpers->getRoleDoesNotExistMessage($name, $guardName));
116 49
        }
117 2
118 2
        return $role;
119
    }
120
121 47
    /**
122
     * A role belongs to some users of the model associated with its guard.
123
     * @return BelongsToMany
124
     */
125
    public function users(): BelongsToMany
126
    {
127
        return $this->belongsToMany($this->helpers->getModelForGuard($this->attributes['guard_name']));
128
    }
129
130
    /**
131
     * Determine if the user may perform the given permission.
132
     *
133
     * @param string|Permission $permission
134 12
     *
135
     * @return bool
136 12
     *
137 9
     * @throws GuardDoesNotMatch
138
     * @throws ReflectionException
139
     */
140 11
    public function hasPermissionTo($permission): bool
141 1
    {
142 1
        if (\is_string($permission)) {
143
            $permission = $this->getPermissionClass()->findByName($permission, $this->getDefaultGuardName());
144 1
        }
145
146
        if (!$this->getGuardNames()->contains($permission->guard_name)) {
147 10
            $expected = $this->getGuardNames();
148
            $given = $permission->guard_name;
149
150
            throw new GuardDoesNotMatch($this->helpers->getGuardDoesNotMatchMessage($expected, $given));
151
        }
152
153
        return $this->permissions->contains('id', $permission->id);
0 ignored issues
show
Bug Best Practice introduced by
The property permissions does not exist on Maklad\Permission\Models\Role. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method contains() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
        return $this->permissions->/** @scrutinizer ignore-call */ contains('id', $permission->id);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
154
    }
155
}
156