Completed
Pull Request — develop (#147)
by Abdelrahman
02:23
created

Ability::boot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
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 $touches = [
50
        'roles',
51
        'users',
52
    ];
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    protected $fillable = [
58
        'name',
59
        'action',
60
        'resource',
61
        'policy',
62
        'description',
63
        'roles',
64
    ];
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    protected $casts = [
70
        'action' => 'string',
71
        'resource' => 'string',
72
        'policy' => 'string',
73
        'deleted_at' => 'datetime',
74
    ];
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    protected $observables = [
80
        'validating',
81
        'validated',
82
    ];
83
84
    /**
85
     * The attributes that are translatable.
86
     *
87
     * @var array
88
     */
89
    public $translatable = [
90
        'name',
91
        'description',
92
    ];
93
94
    /**
95
     * The default rules that the model will validate against.
96
     *
97
     * @var array
98
     */
99
    protected $rules = [];
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    protected $validationMessages = [
105
        'action.unique' => 'The combination of (action & resource) fields has already been taken.',
106
        'resource.unique' => 'The combination of (action & resource) fields has already been taken.',
107
    ];
108
109
    /**
110
     * Whether the model should throw a
111
     * ValidationException if it fails validation.
112
     *
113
     * @var bool
114
     */
115
    protected $throwValidationExceptions = true;
116
117
    /**
118
     * Create a new Eloquent model instance.
119
     *
120
     * @param array $attributes
121
     */
122
    public function __construct(array $attributes = [])
123
    {
124
        parent::__construct($attributes);
125
126
        $this->setTable(config('rinvex.fort.tables.abilities'));
127
        $this->setRules([
128
            'name' => 'required|string|max:150',
129
            '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...
130
            '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...
131
            'policy' => 'nullable|string',
132
            'description' => 'nullable|string|max:10000',
133
        ]);
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    protected static function boot()
140
    {
141
        parent::boot();
142
143
        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...
144
            app('rinvex.fort.role')->forgetCache();
145
            app('rinvex.fort.user')->forgetCache();
146
        });
147
148
        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...
149
            app('rinvex.fort.role')->forgetCache();
150
            app('rinvex.fort.user')->forgetCache();
151
        });
152
    }
153
154
    /**
155
     * An ability can be applied to roles.
156
     *
157
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
158
     */
159
    public function roles()
160
    {
161
        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...
162
                    ->withTimestamps();
163
    }
164
165
    /**
166
     * An ability can be applied to users.
167
     *
168
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
169
     */
170
    public function users()
171
    {
172
        $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...
173
174
        return $this->belongsToMany($userModel, config('rinvex.fort.tables.ability_user'), 'ability_id', 'user_id')
175
                    ->withTimestamps();
176
    }
177
178
    /**
179
     * Determine if the ability is super admin.
180
     *
181
     * @return bool
182
     */
183
    public function isSuperadmin()
184
    {
185
        return $this->action === 'superadmin' && $this->resource === 'global' && ! $this->policy;
186
    }
187
188
    /**
189
     * Determine if the ability is protected.
190
     *
191
     * @return bool
192
     */
193
    public function isProtected()
194
    {
195
        return in_array($this->getKey(), config('rinvex.fort.protected.abilities'));
196
    }
197
198
    /**
199
     * Get slug attribute out of ability's action & resource.
200
     *
201
     * @return string
202
     */
203
    public function getSlugAttribute()
204
    {
205
        return $this->action.'-'.$this->resource;
206
    }
207
208
    /**
209
     * Attach the ability roles.
210
     *
211
     * @param mixed $roles
212
     *
213
     * @return void
214
     */
215
    public function setRolesAttribute($roles)
216
    {
217
        static::saved(function (self $model) use ($roles) {
218
            $model->roles()->sync($roles);
219
        });
220
    }
221
}
222