Completed
Push — master ( f9e78a...edb43e )
by Abdelrahman
09:22
created

Ability::prepareUniqueRule()   C

Complexity

Conditions 11
Paths 40

Size

Total Lines 37
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 16
nc 40
nop 2
dl 0
loc 37
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
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Fort Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Fort Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Fort\Models;
17
18
use Watson\Validating\ValidatingTrait;
19
use Rinvex\Cacheable\CacheableEloquent;
20
use Illuminate\Database\Eloquent\Model;
21
use Spatie\Translatable\HasTranslations;
22
23
/**
24
 * Rinvex\Fort\Models\Ability.
25
 *
26
 * @property int                                                                      $id
27
 * @property string                                                                   $action
28
 * @property string                                                                   $resource
29
 * @property string                                                                   $policy
30
 * @property string                                                                   $name
31
 * @property string                                                                   $description
32
 * @property \Carbon\Carbon                                                           $created_at
33
 * @property \Carbon\Carbon                                                           $updated_at
34
 * @property \Carbon\Carbon                                                           $deleted_at
35
 * @property-read \Illuminate\Database\Eloquent\Collection|\Rinvex\Fort\Models\Role[] $roles
36
 * @property-read \Illuminate\Database\Eloquent\Collection|\Rinvex\Fort\Models\User[] $users
37
 * @property-read bool                                                                $slug
38
 *
39
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereId($value)
40
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereAction($value)
41
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereResource($value)
42
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability wherePolicy($value)
43
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereTitle($value)
44
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereDescription($value)
45
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereCreatedAt($value)
46
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereUpdatedAt($value)
47
 * @method static \Illuminate\Database\Query\Builder|\Rinvex\Fort\Models\Ability whereDeletedAt($value)
48
 * @mixin \Illuminate\Database\Eloquent\Model
49
 */
50
class Ability extends Model
51
{
52
    use HasTranslations;
53
    use ValidatingTrait;
54
    use CacheableEloquent;
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    protected $fillable = [
60
        'action',
61
        'resource',
62
        'policy',
63
        'name',
64
        'description',
65
    ];
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    protected $observables = ['validating', 'validated'];
71
72
    /**
73
     * The attributes that are translatable.
74
     *
75
     * @var array
76
     */
77
    public $translatable = [
78
        'name',
79
        'description',
80
    ];
81
82
    /**
83
     * The default rules that the model will validate against.
84
     *
85
     * @var array
86
     */
87
    protected $rules = [];
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    protected $validationMessages = [
93
        'action.unique' => 'The combination of (action & resource) fields has already been taken.',
94
        'resource.unique' => 'The combination of (action & resource) fields has already been taken.',
95
    ];
96
97
    /**
98
     * Whether the model should throw a ValidationException if it fails validation.
99
     *
100
     * @var bool
101
     */
102
    protected $throwValidationExceptions = true;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $throwValidationExceptions exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
103
104
    /**
105
     * Create a new Eloquent model instance.
106
     *
107
     * @param array $attributes
108
     */
109
    public function __construct(array $attributes = [])
110
    {
111
        parent::__construct($attributes);
112
113
        $this->setTable(config('rinvex.fort.tables.abilities'));
114
        $this->addObservableEvents(['attaching', 'attached', 'detaching', 'detached']);
115
        $this->setRules([
116
            'name' => 'required',
117
            'action' => 'required|unique:'.config('rinvex.fort.tables.abilities').',action,NULL,id,resource,'.$this->resource,
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
118
            'resource' => 'required|unique:'.config('rinvex.fort.tables.abilities').',resource,NULL,id,action,'.$this->action,
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
119
        ]);
120
    }
121
122
    /**
123
     * Register an attaching ability event with the dispatcher.
124
     *
125
     * @param \Closure|string $callback
126
     *
127
     * @return void
128
     */
129
    public static function attaching($callback)
130
    {
131
        static::registerModelEvent('attaching', $callback);
132
    }
133
134
    /**
135
     * Register an attached ability event with the dispatcher.
136
     *
137
     * @param \Closure|string $callback
138
     *
139
     * @return void
140
     */
141
    public static function attached($callback)
142
    {
143
        static::registerModelEvent('attached', $callback);
144
    }
145
146
    /**
147
     * Register a detaching ability event with the dispatcher.
148
     *
149
     * @param \Closure|string $callback
150
     *
151
     * @return void
152
     */
153
    public static function detaching($callback)
154
    {
155
        static::registerModelEvent('detaching', $callback);
156
    }
157
158
    /**
159
     * Register a detached ability event with the dispatcher.
160
     *
161
     * @param \Closure|string $callback
162
     *
163
     * @return void
164
     */
165
    public static function detached($callback)
166
    {
167
        static::registerModelEvent('detached', $callback);
168
    }
169
170
    /**
171
     * An ability can be applied to roles.
172
     *
173
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
174
     */
175
    public function roles()
176
    {
177
        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...
178
                    ->withTimestamps();
179
    }
180
181
    /**
182
     * An ability can be applied to users.
183
     *
184
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
185
     */
186
    public function users()
187
    {
188
        return $this->belongsToMany(config('rinvex.fort.models.user'), config('rinvex.fort.tables.ability_user'), 'ability_id', 'user_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...
189
                    ->withTimestamps();
190
    }
191
192
    /**
193
     * Set the translatable name attribute.
194
     *
195
     * @param string $value
196
     *
197
     * @return void
198
     */
199
    public function setNameAttribute($value)
200
    {
201
        $this->attributes['name'] = json_encode(! is_array($value) ? [app()->getLocale() => $value] : $value);
202
    }
203
204
    /**
205
     * Set the translatable description attribute.
206
     *
207
     * @param string $value
208
     *
209
     * @return void
210
     */
211
    public function setDescriptionAttribute($value)
212
    {
213
        $this->attributes['description'] = ! empty($value) ? json_encode(! is_array($value) ? [app()->getLocale() => $value] : $value) : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 142 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...
214
    }
215
216
    /**
217
     * Determine if the ability is super admin.
218
     *
219
     * @return bool
220
     */
221
    public function isSuperadmin()
222
    {
223
        return ! $this->policy && $this->resource === 'global' && $this->action === 'superadmin';
224
    }
225
226
    /**
227
     * Determine if the ability is protected.
228
     *
229
     * @return bool
230
     */
231
    public function isProtected()
232
    {
233
        return in_array($this->id, config('rinvex.fort.protected.abilities'));
234
    }
235
236
    /**
237
     * Get slug attribute out of ability's action & resource.
238
     *
239
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
240
     */
241
    public function getSlugAttribute()
242
    {
243
        return $this->action.'-'.$this->resource;
244
    }
245
246
    /**
247
     * Prepare a unique rule, adding the table name, column and model indetifier
248
     * if required.
249
     *
250
     * @param array  $parameters
251
     * @param string $field
252
     *
253
     * @return string
254
     */
255
    protected function prepareUniqueRule($parameters, $field)
256
    {
257
        // If the table name isn't set, infer it.
258
        if (empty($parameters[0])) {
259
            $parameters[0] = $this->getModel()->getTable();
260
        }
261
262
        // If the connection name isn't set but exists, infer it.
263
        if ((strpos($parameters[0], '.') === false) && (($connectionName = $this->getModel()->getConnectionName()) !== null)) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 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...
264
            $parameters[0] = $connectionName.'.'.$parameters[0];
265
        }
266
267
        // If the field name isn't get, infer it.
268
        if (! isset($parameters[1])) {
269
            $parameters[1] = $field;
270
        }
271
272
        if ($this->exists) {
273
            // If the identifier isn't set, infer it.
274
            if (! isset($parameters[2]) || strtolower($parameters[2]) === 'null') {
275
                $parameters[2] = $this->getModel()->getKey();
276
            }
277
278
            // If the primary key isn't set, infer it.
279
            if (! isset($parameters[3])) {
280
                $parameters[3] = $this->getModel()->getKeyName();
281
            }
282
283
            foreach ($parameters as $key => $parameter) {
284
                if (strtolower($parameter) === 'null') {
285
                    $parameters[$key] = $this->getModel()->{$parameters[$key - 1]};
286
                }
287
            }
288
        }
289
290
        return 'unique:'.implode(',', $parameters);
291
    }
292
}
293