Completed
Push — develop ( d46ae7...fe6218 )
by Abdelrahman
03:07
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\Support\Traits\HasTranslations;
10
use Rinvex\Support\Traits\ValidatingTrait;
11
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
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
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
     * An ability can be applied to roles.
138
     *
139
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
140
     */
141
    public function roles(): BelongsToMany
142
    {
143
        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...
144
                    ->withTimestamps();
145
    }
146
147
    /**
148
     * An ability can be applied to users.
149
     *
150
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
151
     */
152
    public function users(): BelongsToMany
153
    {
154
        $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...
155
156
        return $this->belongsToMany($userModel, config('rinvex.fort.tables.ability_user'), 'ability_id', 'user_id')
157
                    ->withTimestamps();
158
    }
159
160
    /**
161
     * Determine if the ability is super admin.
162
     *
163
     * @return bool
164
     */
165
    public function isSuperadmin(): bool
166
    {
167
        return $this->action === 'superadmin' && $this->resource === 'global' && ! $this->policy;
168
    }
169
170
    /**
171
     * Determine if the ability is protected.
172
     *
173
     * @return bool
174
     */
175
    public function isProtected(): bool
176
    {
177
        return in_array($this->getKey(), config('rinvex.fort.protected.abilities'));
178
    }
179
180
    /**
181
     * Get slug attribute out of ability's action & resource.
182
     *
183
     * @return string
184
     */
185
    public function getSlugAttribute(): string
186
    {
187
        return $this->action.'-'.$this->resource;
188
    }
189
190
    /**
191
     * Attach the ability roles.
192
     *
193
     * @param mixed $roles
194
     *
195
     * @return void
196
     */
197
    public function setRolesAttribute($roles): void
198
    {
199
        static::saved(function (self $model) use ($roles) {
200
            $model->roles()->sync($roles);
201
        });
202
    }
203
}
204