Completed
Push — master ( b6e961...8692a9 )
by Abdelrahman
15:05 queued 12:57
created

Ability::prepareUniqueRule()   C

Complexity

Conditions 11
Paths 40

Size

Total Lines 39
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 16
nc 40
nop 2
dl 0
loc 39
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Fort\Models;
6
7
use Illuminate\Database\Eloquent\Model;
8
use Rinvex\Cacheable\CacheableEloquent;
9
use Rinvex\Fort\Contracts\AbilityContract;
10
use Rinvex\Support\Traits\HasTranslations;
11
use Rinvex\Support\Traits\ValidatingTrait;
12
13
/**
14
 * Rinvex\Fort\Models\Ability.
15
 *
16
 * @property int                                                                      $id
17
 * @property string                                                                   $action
18
 * @property string                                                                   $resource
19
 * @property string                                                                   $policy
20
 * @property array                                                                    $name
21
 * @property array                                                                    $description
22
 * @property \Carbon\Carbon|null                                                      $created_at
23
 * @property \Carbon\Carbon|null                                                      $updated_at
24
 * @property \Carbon\Carbon|null                                                      $deleted_at
25
 * @property-read string                                                              $slug
26
 * @property \Illuminate\Database\Eloquent\Collection|\Rinvex\Fort\Models\Role[]      $roles
27
 * @property-read \Illuminate\Database\Eloquent\Collection|\Rinvex\Fort\Models\User[] $users
28
 *
29
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereAction($value)
30
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereCreatedAt($value)
31
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereDeletedAt($value)
32
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereDescription($value)
33
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereId($value)
34
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereName($value)
35
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability wherePolicy($value)
36
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereResource($value)
37
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Fort\Models\Ability whereUpdatedAt($value)
38
 * @mixin \Eloquent
39
 */
40
class Ability extends Model implements AbilityContract
41
{
42
    use HasTranslations;
43
    use ValidatingTrait;
44
    use CacheableEloquent;
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    protected $fillable = [
50
        'name',
51
        'action',
52
        'resource',
53
        'policy',
54
        'description',
55
        'roles',
56
    ];
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    protected $casts = [
62
        'action' => 'string',
63
        'resource' => 'string',
64
        'policy' => 'string',
65
        'deleted_at' => 'datetime',
66
    ];
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    protected $observables = [
72
        'attaching',
73
        'attached',
74
        'detaching',
75
        'detached',
76
        'validating',
77
        'validated',
78
    ];
79
80
    /**
81
     * The attributes that are translatable.
82
     *
83
     * @var array
84
     */
85
    public $translatable = [
86
        'name',
87
        'description',
88
    ];
89
90
    /**
91
     * The default rules that the model will validate against.
92
     *
93
     * @var array
94
     */
95
    protected $rules = [];
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    protected $validationMessages = [
101
        'action.unique' => 'The combination of (action & resource) fields has already been taken.',
102
        'resource.unique' => 'The combination of (action & resource) fields has already been taken.',
103
    ];
104
105
    /**
106
     * Whether the model should throw a
107
     * ValidationException if it fails validation.
108
     *
109
     * @var bool
110
     */
111
    protected $throwValidationExceptions = true;
112
113
    /**
114
     * Create a new Eloquent model instance.
115
     *
116
     * @param array $attributes
117
     */
118
    public function __construct(array $attributes = [])
119
    {
120
        parent::__construct($attributes);
121
122
        $this->setTable(config('rinvex.fort.tables.abilities'));
123
        $this->setRules([
124
            'name' => 'required|string|max:150',
125
            'action' => 'required|string|unique:'.config('rinvex.fort.tables.abilities').',action,NULL,id,resource,'.($this->resource ?? 'null'),
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 145 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
126
            'resource' => 'required|string|unique:'.config('rinvex.fort.tables.abilities').',resource,NULL,id,action,'.($this->action ?? 'null'),
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 145 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
127
            'policy' => 'nullable|string',
128
            'description' => 'nullable|string|max:10000',
129
        ]);
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    protected static function boot()
136
    {
137
        parent::boot();
138
139
        static::updated(function (self $ability) {
0 ignored issues
show
Unused Code introduced by
The parameter $ability is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
140
            app('rinvex.fort.role')->forgetCache();
141
            app('rinvex.fort.user')->forgetCache();
142
        });
143
144
        static::deleted(function (self $ability) {
0 ignored issues
show
Unused Code introduced by
The parameter $ability is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
145
            app('rinvex.fort.role')->forgetCache();
146
            app('rinvex.fort.user')->forgetCache();
147
        });
148
149
        static::attached(function (self $ability) {
0 ignored issues
show
Unused Code introduced by
The parameter $ability is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
150
            app('rinvex.fort.role')->forgetCache();
151
            app('rinvex.fort.user')->forgetCache();
152
        });
153
154
        static::detached(function (self $ability) {
0 ignored issues
show
Unused Code introduced by
The parameter $ability is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
155
            app('rinvex.fort.role')->forgetCache();
156
            app('rinvex.fort.user')->forgetCache();
157
        });
158
    }
159
160
    /**
161
     * Register an attaching ability event with the dispatcher.
162
     *
163
     * @param \Closure|string $callback
164
     *
165
     * @return void
166
     */
167
    public static function attaching($callback)
168
    {
169
        static::registerModelEvent('attaching', $callback);
170
    }
171
172
    /**
173
     * Register an attached ability event with the dispatcher.
174
     *
175
     * @param \Closure|string $callback
176
     *
177
     * @return void
178
     */
179
    public static function attached($callback)
180
    {
181
        static::registerModelEvent('attached', $callback);
182
    }
183
184
    /**
185
     * Register a detaching ability event with the dispatcher.
186
     *
187
     * @param \Closure|string $callback
188
     *
189
     * @return void
190
     */
191
    public static function detaching($callback)
192
    {
193
        static::registerModelEvent('detaching', $callback);
194
    }
195
196
    /**
197
     * Register a detached ability event with the dispatcher.
198
     *
199
     * @param \Closure|string $callback
200
     *
201
     * @return void
202
     */
203
    public static function detached($callback)
204
    {
205
        static::registerModelEvent('detached', $callback);
206
    }
207
208
    /**
209
     * An ability can be applied to roles.
210
     *
211
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
212
     */
213
    public function roles()
214
    {
215
        return $this->belongsToMany(config('rinvex.fort.models.role'), config('rinvex.fort.tables.ability_role'), 'ability_id', 'role_id')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
216
                    ->withTimestamps();
217
    }
218
219
    /**
220
     * An ability can be applied to users.
221
     *
222
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
223
     */
224
    public function users()
225
    {
226
        $userModel = config('auth.providers.'.config('auth.guards.'.config('auth.defaults.guard').'.provider').'.model');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
227
228
        return $this->belongsToMany($userModel, config('rinvex.fort.tables.ability_user'), 'ability_id', 'user_id')
229
                    ->withTimestamps();
230
    }
231
232
    /**
233
     * Determine if the ability is super admin.
234
     *
235
     * @return bool
236
     */
237
    public function isSuperadmin()
238
    {
239
        return ! $this->policy && $this->resource === 'global' && $this->action === 'superadmin';
240
    }
241
242
    /**
243
     * Determine if the ability is protected.
244
     *
245
     * @return bool
246
     */
247
    public function isProtected()
248
    {
249
        return in_array($this->id, config('rinvex.fort.protected.abilities'));
250
    }
251
252
    /**
253
     * Get slug attribute out of ability's action & resource.
254
     *
255
     * @return string
256
     */
257
    public function getSlugAttribute()
258
    {
259
        return $this->action.'-'.$this->resource;
260
    }
261
262
    /**
263
     * Attach the ability roles.
264
     *
265
     * @param mixed $roles
266
     *
267
     * @return void
268
     */
269
    public function setRolesAttribute($roles)
270
    {
271
        static::saved(function (self $model) use ($roles) {
272
            $model->roles()->sync($roles);
273
        });
274
    }
275
}
276