Completed
Push — master ( 4623fe...be1a12 )
by ARCANEDEV
09:43
created

PermissionsGroup::slugify()   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
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelAuth\Models;
2
3
use Arcanedev\LaravelAuth\Events\PermissionsGroups as PermissionsGroupEvents;
4
use Arcanesoft\Contracts\Auth\Models\Permission as PermissionContract;
5
use Arcanesoft\Contracts\Auth\Models\PermissionsGroup as PermissionsGroupContract;
6
use Illuminate\Database\Eloquent\Model as Eloquent;
7
use Illuminate\Support\Str;
8
9
/**
10
 * Class     PermissionsGroup
11
 *
12
 * @package  Arcanedev\LaravelAuth\Models
13
 * @author   ARCANEDEV <[email protected]>
14
 *
15
 * @property  int                                       id
16
 * @property  string                                    name
17
 * @property  string                                    slug
18
 * @property  string                                    description
19
 * @property  \Carbon\Carbon                            created_at
20
 * @property  \Carbon\Carbon                            updated_at
21
 * @property  \Illuminate\Database\Eloquent\Collection  permissions
22
 */
23
class PermissionsGroup extends AbstractModel implements PermissionsGroupContract
0 ignored issues
show
Bug introduced by
There is one abstract method getKey in this class; you could implement it, or declare this class as abstract.
Loading history...
24
{
25
    /* -----------------------------------------------------------------
26
     |  Properties
27
     | -----------------------------------------------------------------
28
     */
29
    /**
30
     * The attributes that are mass assignable.
31
     *
32
     * @var array
33
     */
34
    protected $fillable = ['name', 'slug', 'description'];
35
36
    /* -----------------------------------------------------------------
37
     |  Constructor
38
     | -----------------------------------------------------------------
39
     */
40
    /**
41
     * Create a new Eloquent model instance.
42
     *
43
     * @param  array  $attributes
44
     */
45 234
    public function __construct(array $attributes = [])
46
    {
47 234
        parent::__construct($attributes);
48
49 234
        $this->setTable(
50 234
            config('laravel-auth.permissions-groups.table', 'permissions_groups')
51 78
        );
52 234
    }
53
54
    /* ------------------------------------------------------------------------------------------------
55
     |  Relationships
56
     | ------------------------------------------------------------------------------------------------
57
     */
58
    /**
59
     * Permissions Groups has many permissions.
60
     *
61
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
62
     */
63 39
    public function permissions()
64
    {
65 39
        return $this->hasMany(
66 39
            config('laravel-auth.permissions.model', Permission::class),
67 26
            'group_id'
68 13
        );
69
    }
70
71
    /* -----------------------------------------------------------------
72
     |  Getters & Setters
73
     | -----------------------------------------------------------------
74
     */
75
    /**
76
     * Set the name attribute.
77
     *
78
     * @param  string  $name
79
     */
80 39
    public function setNameAttribute($name)
81
    {
82 39
        $this->attributes['name'] = $name;
83 39
        $this->setSlugAttribute($name);
84 39
    }
85
86
    /**
87
     * Set the slug attribute.
88
     *
89
     * @param  string  $slug
90
     */
91 39
    public function setSlugAttribute($slug)
92
    {
93 39
        $this->attributes['slug'] = Str::slug($slug, config('laravel-auth.permissions-groups.slug-separator', '-'));
94 39
    }
95
96
    /* -----------------------------------------------------------------
97
     |  Main Methods
98
     | -----------------------------------------------------------------
99
     */
100
    /**
101
     * Create and attach a permission.
102
     *
103
     * @param  array  $attributes
104
     * @param  bool   $reload
105
     */
106 6
    public function createPermission(array $attributes, $reload = true)
107
    {
108 6
        event(new PermissionsGroupEvents\CreatingPermission($this, $attributes));
109 6
        $permission = $this->permissions()->create($attributes);
110 6
        event(new PermissionsGroupEvents\CreatedPermission($this, $permission));
111
112 6
        $this->loadPermissions($reload);
113 6
    }
114
115
    /**
116
     * Attach the permission to a group.
117
     *
118
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission  $permission
119
     * @param  bool                                          $reload
120
     */
121 18
    public function attachPermission(&$permission, $reload = true)
122
    {
123 18
        if ($this->hasPermission($permission)) return;
124
125 18
        event(new PermissionsGroupEvents\AttachingPermissionToGroup($this, $permission));
126 18
        $permission = $this->permissions()->save($permission);
127 18
        event(new PermissionsGroupEvents\AttachedPermissionToGroup($this, $permission));
128
129 18
        $this->loadPermissions($reload);
130 18
    }
131
132
    /**
133
     * Attach the permission by id to a group.
134
     *
135
     * @param  int   $id
136
     * @param  bool  $reload
137
     *
138
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
139
     */
140 3
    public function attachPermissionById($id, $reload = true)
141
    {
142 3
        $permission = $this->getPermissionById($id);
143
144 3
        if ($permission !== null) $this->attachPermission($permission, $reload);
145
146 3
        return $permission;
147
    }
148
149
    /**
150
     * Attach a collection of permissions to the group.
151
     *
152
     * @param  \Illuminate\Database\Eloquent\Collection|array  $permissions
153
     * @param  bool                                            $reload
154
     *
155
     * @return \Illuminate\Database\Eloquent\Collection|array
156
     */
157 9
    public function attachPermissions($permissions, $reload = true)
158
    {
159 9
        event(new PermissionsGroupEvents\AttachingPermissionsToGroup($this, $permissions));
160 9
        $permissions = $this->permissions()->saveMany($permissions);
161 9
        event(new PermissionsGroupEvents\AttachedPermissionsToGroup($this, $permissions));
162
163 9
        $this->loadPermissions($reload);
164
165 9
        return $permissions;
166
    }
167
168
    /**
169
     * Attach the permission from a group.
170
     *
171
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission  $permission
172
     * @param  bool                                          $reload
173
     */
174 9
    public function detachPermission(&$permission, $reload = true)
175
    {
176 9
        if ( ! $this->hasPermission($permission)) return;
177
178
        /** @var  \Arcanesoft\Contracts\Auth\Models\Permission  $permission */
179 9
        $permission = $this->getPermissionFromGroup($permission);
180
181 9
        event(new PermissionsGroupEvents\DetachingPermissionFromGroup($this, $permission));
182 9
        $permission->update(['group_id' => 0]);
0 ignored issues
show
Bug introduced by
The method update() does not seem to exist on object<Arcanesoft\Contra...Auth\Models\Permission>.

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...
183 9
        event(new PermissionsGroupEvents\DetachedPermissionFromGroup($this, $permission));
184
185 9
        $this->loadPermissions($reload);
186 9
    }
187
188
    /**
189
     * Attach the permission by id to a group.
190
     *
191
     * @param  int   $id
192
     * @param  bool  $reload
193
     *
194
     * @return \Arcanesoft\Contracts\Auth\Models\Permission
195
     */
196 3
    public function detachPermissionById($id, $reload = true)
197
    {
198 3
        if ( ! is_null($permission = $this->getPermissionById($id)))
199 3
            $this->detachPermission($permission, $reload);
200
201 3
        return $permission;
202
    }
203
204
    /**
205
     * Detach multiple permissions by ids.
206
     *
207
     * @param  array  $ids
208
     * @param  bool   $reload
209
     *
210
     * @return int
211
     */
212 3
    public function detachPermissions(array $ids, $reload = true)
213
    {
214 3
        event(new PermissionsGroupEvents\DetachingPermissionsFromGroup($this, $ids));
215 3
        $detached = $this->permissions()->whereIn('id', $ids)->update(['group_id' => 0]);
216 3
        event(new PermissionsGroupEvents\DetachedPermissionsFromGroup($this, $ids, $detached));
217
218 3
        $this->loadPermissions($reload);
219
220 3
        return $detached;
221
    }
222
223
    /**
224
     * Detach all permissions from the group.
225
     *
226
     * @param  bool  $reload
227
     *
228
     * @return int
229
     */
230 6
    public function detachAllPermissions($reload = true)
231
    {
232 6
        event(new PermissionsGroupEvents\DetachingAllPermissionsFromGroup($this));
233 6
        $detached = $this->permissions()->update(['group_id' => 0]);
234 6
        event(new PermissionsGroupEvents\DetachedAllPermissionsFromGroup($this, $detached));
235
236 6
        $this->loadPermissions($reload);
237
238 6
        return $detached;
239
    }
240
241
    /* -----------------------------------------------------------------
242
     |  Check Methods
243
     | -----------------------------------------------------------------
244
     */
245
    /**
246
     * Check if role has the given permission (Permission Model or Id).
247
     *
248
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $id
249
     *
250
     * @return bool
251
     */
252 24
    public function hasPermission($id)
253
    {
254 24
        if ($id instanceof Eloquent) $id = $id->getKey();
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...
255
256 24
        return $this->getPermissionFromGroup($id) !== null;
257
    }
258
259
    /* -----------------------------------------------------------------
260
     |  Other Methods
261
     | -----------------------------------------------------------------
262
     */
263
    /**
264
     * Get a permission from the group.
265
     *
266
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $id
267
     *
268
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
269
     */
270 24
    private function getPermissionFromGroup($id)
271
    {
272 24
        if ($id instanceof Eloquent) $id = $id->getKey();
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...
273
274 24
        $this->loadPermissions();
275
276 24
        return $this->permissions
277 24
            ->filter(function (PermissionContract $permission) use ($id) {
278 24
                return $permission->getKey() == $id;
279 24
            })
280 24
            ->first();
281
    }
282
283
    /**
284
     * Get a permission by id.
285
     *
286
     * @param  int  $id
287
     *
288
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
289
     */
290 6
    private function getPermissionById($id)
291
    {
292 6
        return $this->permissions()->getRelated()->where('id', $id)->first();
293
    }
294
295
    /**
296
     * Load the permissions.
297
     *
298
     * @param  bool  $load
299
     *
300
     * @return self
301
     */
302 33
    protected function loadPermissions($load = true)
303
    {
304 33
        return $load ? $this->load('permissions') : $this;
305
    }
306
}
307