Completed
Pull Request — master (#23)
by ARCANEDEV
09:06
created

Role::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
ccs 4
cts 4
cp 1
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelAuth\Models;
2
3
use Arcanedev\LaravelAuth\Bases\Model;
4
use Arcanedev\LaravelAuth\Models\Traits\Activatable;
5
use Arcanesoft\Contracts\Auth\Models\Permission as PermissionContract;
6
use Arcanesoft\Contracts\Auth\Models\Role as RoleContract;
7
use Illuminate\Database\Eloquent\Model as Eloquent;
8
use Illuminate\Support\Str;
9
10
/**
11
 * Class     Role
12
 *
13
 * @package  Arcanedev\LaravelAuth\Models
14
 * @author   ARCANEDEV <[email protected]>
15
 *
16
 * @property  int                                       id
17
 * @property  string                                    name
18
 * @property  string                                    slug
19
 * @property  string                                    description
20
 * @property  bool                                      is_active
21
 * @property  bool                                      is_locked
22
 * @property  \Carbon\Carbon                            created_at
23
 * @property  \Carbon\Carbon                            updated_at
24
 *
25
 * @property  \Illuminate\Database\Eloquent\Collection       users
26
 * @property  \Illuminate\Database\Eloquent\Collection       permissions
27
 * @property  \Arcanedev\LaravelAuth\Models\Pivots\RoleUser  pivot
28
 */
29
class Role extends Model implements RoleContract
30
{
31
    /* ------------------------------------------------------------------------------------------------
32
     |  Traits
33
     | ------------------------------------------------------------------------------------------------
34
     */
35
    use Activatable;
36
37
    /* ------------------------------------------------------------------------------------------------
38
     |  Properties
39
     | ------------------------------------------------------------------------------------------------
40
     */
41
    /**
42
     * The attributes that are mass assignable.
43
     *
44
     * @var array
45
     */
46
    protected $fillable = ['name', 'slug', 'description'];
47
48
    /**
49
     * The attributes that should be casted to native types.
50
     *
51
     * @var array
52
     */
53
    protected $casts = [
54
        'is_active' => 'boolean',
55
        'is_locked' => 'boolean',
56
    ];
57
58
    /* ------------------------------------------------------------------------------------------------
59
     |  Constructor
60
     | ------------------------------------------------------------------------------------------------
61
     */
62
    /**
63
     * Create a new Eloquent model instance.
64
     *
65
     * @param  array  $attributes
66
     */
67 225
    public function __construct(array $attributes = [])
68
    {
69 225
        $this->setTable(config('laravel-auth.roles.table', 'roles'));
70
71 225
        parent::__construct($attributes);
72 225
    }
73
74
    /* ------------------------------------------------------------------------------------------------
75
     |  Relationships
76
     | ------------------------------------------------------------------------------------------------
77
     */
78
    /**
79
     * Role belongs to many users.
80
     *
81
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
82
     */
83 15
    public function users()
84
    {
85
        return $this
86 15
            ->belongsToMany(
87 15
                config('laravel-auth.users.model', User::class),
88 15
                $this->getPrefix().config('laravel-auth.role-user.table', 'permission_role')
89
            )
90 15
            ->using(Pivots\RoleUser::class)
91 15
            ->withTimestamps();
92
    }
93
94
    /**
95
     * Role belongs to many permissions.
96
     *
97
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
98
     */
99 33
    public function permissions()
100
    {
101
        return $this
102 33
            ->belongsToMany(
103 33
                config('laravel-auth.permissions.model', Permission::class),
104 33
                $this->getPrefix().config('laravel-auth.permission-role.table', 'permission_role')
105
            )
106 33
            ->using(Pivots\PermissionRole::class)
107 33
            ->withTimestamps();
108
    }
109
110
    /* ------------------------------------------------------------------------------------------------
111
     |  Getters & Setters
112
     | ------------------------------------------------------------------------------------------------
113
     */
114
    /**
115
     * Set the name attribute.
116
     *
117
     * @param  string  $name
118
     */
119 90
    public function setNameAttribute($name)
120
    {
121 90
        $this->attributes['name'] = $name;
122 90
        $this->setSlugAttribute($name);
123 90
    }
124
125
    /**
126
     * Set the slug attribute.
127
     *
128
     * @param  string  $slug
129
     */
130 90
    public function setSlugAttribute($slug)
131
    {
132 90
        $this->attributes['slug'] = $this->slugify($slug);
133 90
    }
134
135
    /* ------------------------------------------------------------------------------------------------
136
     |  CRUD Functions
137
     | ------------------------------------------------------------------------------------------------
138
     */
139
    /**
140
     * Attach a permission to a role.
141
     *
142
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $user
143
     * @param  bool                                        $reload
144
     */
145 9
    public function attachUser($user, $reload = true)
146
    {
147 9
        if ( ! $this->hasUser($user)) {
148 9
            $this->users()->attach($user);
149 9
            $this->loadUsers($reload);
150
        }
151 9
    }
152
153
    /**
154
     * Detach a user from a role.
155
     *
156
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $user
157
     * @param  bool                                        $reload
158
     *
159
     * @return int
160
     */
161 3
    public function detachUser($user, $reload = true)
162
    {
163 3
        if ($user instanceof Eloquent)
0 ignored issues
show
Bug introduced by
The class Illuminate\Database\Eloquent\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
164 3
            $user = (array) $user->getKey();
165
166 3
        $result = $this->users()->detach($user);
167 3
        $this->loadUsers($reload);
168
169 3
        return $result;
170
    }
171
172
    /**
173
     * Detach all users from a role.
174
     *
175
     * @param  bool  $reload
176
     *
177
     * @return int
178
     */
179 3
    public function detachAllUsers($reload = true)
180
    {
181 3
        $result = $this->users()->detach();
182 3
        $this->loadUsers($reload);
183
184 3
        return $result;
185
    }
186
187
    /**
188
     * Check if role has the given user (User Model or Id).
189
     *
190
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $id
191
     *
192
     * @return bool
193
     */
194 9
    public function hasUser($id)
195
    {
196 9
        if ($id instanceof Eloquent)
0 ignored issues
show
Bug introduced by
The class Illuminate\Database\Eloquent\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
197 9
            $id = $id->getKey();
198
199 9
        return $this->users->contains($id);
200
    }
201
202
    /**
203
     * Attach a permission to a role.
204
     *
205
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $permission
206
     * @param  bool                                              $reload
207
     */
208 27
    public function attachPermission($permission, $reload = true)
209
    {
210 27
        if ( ! $this->hasPermission($permission)) {
211 27
            $this->permissions()->attach($permission);
212 27
            $this->loadPermissions($reload);
213
        }
214 27
    }
215
216
    /**
217
     * Detach a permission from a role.
218
     *
219
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $permission
220
     * @param  bool                                              $reload
221
     *
222
     * @return int
223
     */
224 3
    public function detachPermission($permission, $reload = true)
225
    {
226 3
        if ($permission instanceof Eloquent)
0 ignored issues
show
Bug introduced by
The class Illuminate\Database\Eloquent\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
227 3
            $permission = (array) $permission->getKey();
228
229 3
        $result = $this->permissions()->detach($permission);
230 3
        $this->loadPermissions($reload);
231
232 3
        return $result;
233
    }
234
235
    /**
236
     * Detach all permissions from a role.
237
     *
238
     * @param  bool  $reload
239
     *
240
     * @return int
241
     */
242 3
    public function detachAllPermissions($reload = true)
243
    {
244 3
        $result = $this->permissions()->detach();
245 3
        $this->loadPermissions($reload);
246
247 3
        return $result;
248
    }
249
250
    /**
251
     * Check if role has the given permission (Permission Model or Id).
252
     *
253
     * @param  mixed  $id
254
     *
255
     * @return bool
256
     */
257 27
    public function hasPermission($id)
258
    {
259 27
        if ($id instanceof Eloquent)
0 ignored issues
show
Bug introduced by
The class Illuminate\Database\Eloquent\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
260 27
            $id = $id->getKey();
261
262 27
        return $this->permissions->contains($id);
263
    }
264
265
    /* ------------------------------------------------------------------------------------------------
266
     |  Check Functions
267
     | ------------------------------------------------------------------------------------------------
268
     */
269
    /**
270
     * Check if role is associated with a permission by slug.
271
     *
272
     * @param  string  $slug
273
     *
274
     * @return bool
275
     */
276
    public function can($slug)
277
    {
278 9
        $permissions = $this->permissions->filter(function(PermissionContract $permission) use ($slug) {
279 9
            return $permission->checkSlug($slug);
280 9
        });
281
282 9
        return $permissions->count() === 1;
283
    }
284
285
    /**
286
     * Check if a role is associated with any of given permissions.
287
     *
288
     * @param  array  $permissions
289
     * @param  array  &$failedPermissions
290
     *
291
     * @return bool
292
     */
293 6
    public function canAny(array $permissions, array &$failedPermissions = [])
294
    {
295 6
        foreach ($permissions as $permission) {
296 6
            if ( ! $this->can($permission))
297 6
                $failedPermissions[] = $permission;
298
        }
299
300 6
        return count($permissions) !== count($failedPermissions);
301
    }
302
303
    /**
304
     * Check if role is associated with all given permissions.
305
     *
306
     * @param  array  $permissions
307
     * @param  array  &$failedPermissions
308
     *
309
     * @return bool
310
     */
311 3
    public function canAll(array $permissions, array &$failedPermissions = [])
312
    {
313 3
        $this->canAny($permissions, $failedPermissions);
314
315 3
        return count($failedPermissions) === 0;
316
    }
317
318
    /**
319
     * Check if the role is locked.
320
     *
321
     * @return bool
322
     */
323 6
    public function isLocked()
324
    {
325 6
        return $this->is_locked;
326
    }
327
328
    /**
329
     * Check if slug is the same as the given value.
330
     *
331
     * @param  string  $value
332
     *
333
     * @return bool
334
     */
335 18
    public function checkSlug($value)
336
    {
337 18
        return $this->slug === $this->slugify($value);
338
    }
339
340
    /* ------------------------------------------------------------------------------------------------
341
     |  Other Functions
342
     | ------------------------------------------------------------------------------------------------
343
     */
344
    /**
345
     * Load the users.
346
     *
347
     * @param  bool  $load
348
     *
349
     * @return self
350
     */
351 9
    protected function loadUsers($load = true)
352
    {
353 9
        return $load ? $this->load('users') : $this;
354
    }
355
356
    /**
357
     * Load the permissions.
358
     *
359
     * @param  bool  $load
360
     *
361
     * @return self
362
     */
363 27
    protected function loadPermissions($load = true)
364
    {
365 27
        return $load ? $this->load('permissions') : $this;
366
    }
367
368
    /**
369
     * Slugify the value.
370
     *
371
     * @param  string  $value
372
     *
373
     * @return string
374
     */
375 90
    protected function slugify($value)
376
    {
377 90
        return Str::slug($value, config('laravel-auth.roles.slug-separator', '-'));
378
    }
379
}
380