Completed
Push — develop ( 29bb06...3a0764 )
by Abdelrahman
02:04
created

User::setRolesAttribute()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Models;
6
7
use Rinvex\Country\Country;
8
use Rinvex\Language\Language;
9
use Rinvex\Tags\Traits\Taggable;
10
use Illuminate\Auth\Authenticatable;
11
use Illuminate\Support\Facades\Hash;
12
use Rinvex\Auth\Traits\HasHashables;
13
use Rinvex\Auth\Traits\CanVerifyEmail;
14
use Rinvex\Auth\Traits\CanVerifyPhone;
15
use Cortex\Foundation\Traits\Auditable;
16
use Illuminate\Database\Eloquent\Model;
17
use Rinvex\Cacheable\CacheableEloquent;
18
use Rinvex\Support\Traits\HashidsTrait;
19
use Illuminate\Notifications\Notifiable;
20
use Rinvex\Auth\Traits\CanResetPassword;
21
use Rinvex\Support\Traits\ValidatingTrait;
22
use Spatie\Activitylog\Traits\HasActivity;
23
use Spatie\MediaLibrary\HasMedia\HasMedia;
24
use Rinvex\Support\Traits\HasSocialAttributes;
25
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
26
use Rinvex\Auth\Traits\AuthenticatableTwoFactor;
27
use Rinvex\Auth\Contracts\CanVerifyEmailContract;
28
use Rinvex\Auth\Contracts\CanVerifyPhoneContract;
29
use Silber\Bouncer\Database\HasRolesAndAbilities;
30
use Illuminate\Foundation\Auth\Access\Authorizable;
31
use Rinvex\Auth\Contracts\CanResetPasswordContract;
32
use Illuminate\Database\Eloquent\Relations\MorphMany;
33
use Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract;
34
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
35
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
36
37
abstract class User extends Model implements AuthenticatableContract, AuthenticatableTwoFactorContract, AuthorizableContract, CanResetPasswordContract, CanVerifyEmailContract, CanVerifyPhoneContract, HasMedia
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 208 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...
38
{
39
    // @TODO: Strangely, this issue happens only here!!!
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
40
    // Duplicate trait usage to fire attached events for cache
41
    // flush before other events in other traits specially HasActivity,
42
    // otherwise old cached queries used and no changelog recorded on update.
43
    use CacheableEloquent;
44
    use Taggable;
45
    use Auditable;
46
    use Notifiable;
47
    use HasActivity;
48
    use HashidsTrait;
49
    use Authorizable;
50
    use HasHashables;
51
    use HasMediaTrait;
52
    use CanVerifyEmail;
53
    use CanVerifyPhone;
54
    use Authenticatable;
55
    use ValidatingTrait;
56
    use CanResetPassword;
57
    use HasSocialAttributes;
58
    use HasRolesAndAbilities;
59
    use AuthenticatableTwoFactor;
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected $fillable = [
65
        'username',
66
        'password',
67
        'two_factor',
68
        'email',
69
        'email_verified',
70
        'email_verified_at',
71
        'phone',
72
        'phone_verified',
73
        'phone_verified_at',
74
        'given_name',
75
        'family_name',
76
        'title',
77
        'organization',
78
        'country_code',
79
        'language_code',
80
        'birthday',
81
        'gender',
82
        'social',
83
        'is_active',
84
        'last_activity',
85
        'abilities',
86
        'roles',
87
        'tags',
88
    ];
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    protected $casts = [
94
        'username' => 'string',
95
        'password' => 'string',
96
        'two_factor' => 'json',
97
        'email' => 'string',
98
        'email_verified' => 'boolean',
99
        'email_verified_at' => 'datetime',
100
        'phone' => 'string',
101
        'phone_verified' => 'boolean',
102
        'phone_verified_at' => 'datetime',
103
        'given_name' => 'string',
104
        'family_name' => 'string',
105
        'title' => 'string',
106
        'organization' => 'string',
107
        'country_code' => 'string',
108
        'language_code' => 'string',
109
        'birthday' => 'string',
110
        'gender' => 'string',
111
        'social' => 'array',
112
        'is_active' => 'boolean',
113
        'last_activity' => 'datetime',
114
        'deleted_at' => 'datetime',
115
    ];
116
117
    /**
118
     * {@inheritdoc}
119
     */
120
    protected $hidden = [
121
        'password',
122
        'two_factor',
123
        'remember_token',
124
    ];
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    protected $observables = [
130
        'validating',
131
        'validated',
132
    ];
133
134
    /**
135
     * The attributes to be encrypted before saving.
136
     *
137
     * @var array
138
     */
139
    protected $hashables = [
140
        'password',
141
    ];
142
143
    /**
144
     * The default rules that the model will validate against.
145
     *
146
     * @var array
147
     */
148
    protected $rules = [];
149
150
    /**
151
     * Whether the model should throw a
152
     * ValidationException if it fails validation.
153
     *
154
     * @var bool
155
     */
156
    protected $throwValidationExceptions = true;
157
158
    /**
159
     * Indicates whether to log only dirty attributes or all.
160
     *
161
     * @var bool
162
     */
163
    protected static $logOnlyDirty = true;
164
165
    /**
166
     * The attributes that are logged on change.
167
     *
168
     * @var array
169
     */
170
    protected static $logFillable = true;
171
172
    /**
173
     * The attributes that are ignored on change.
174
     *
175
     * @var array
176
     */
177
    protected static $ignoreChangedAttributes = [
178
        'password',
179
        'two_factor',
180
        'email_verified_at',
181
        'phone_verified_at',
182
        'last_activity',
183
        'created_at',
184
        'updated_at',
185
        'deleted_at',
186
    ];
187
188
    /**
189
     * Register media collections.
190
     *
191
     * @return void
192
     */
193
    public function registerMediaCollections(): void
194
    {
195
        $this->addMediaCollection('profile_picture')->singleFile();
196
        $this->addMediaCollection('cover_photo')->singleFile();
197
    }
198
199
    /**
200
     * Attach the given abilities to the model.
201
     *
202
     * @param mixed $abilities
203
     *
204
     * @return void
205
     */
206
    public function setAbilitiesAttribute($abilities): void
207
    {
208
        static::saved(function (self $model) use ($abilities) {
209
            $abilities = collect($abilities)->filter();
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $abilities, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
210
211
            $model->abilities->pluck('id')->similar($abilities)
212
            || activity()
213
                ->performedOn($model)
214
                ->withProperties(['attributes' => ['abilities' => $abilities], 'old' => ['abilities' => $model->abilities->pluck('id')->toArray()]])
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 148 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...
215
                ->log('updated');
216
217
            $model->abilities()->sync($abilities, true);
218
        });
219
    }
220
221
    /**
222
     * Attach the given roles to the model.
223
     *
224
     * @param mixed $roles
225
     *
226
     * @return void
227
     */
228
    public function setRolesAttribute($roles): void
229
    {
230
        static::saved(function (self $model) use ($roles) {
231
            $roles = collect($roles)->filter();
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $roles, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
232
233
            $model->roles->pluck('id')->similar($roles)
234
            || activity()
235
                ->performedOn($model)
236
                ->withProperties(['attributes' => ['roles' => $roles], 'old' => ['roles' => $model->roles->pluck('id')->toArray()]])
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 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...
237
                ->log('updated');
238
239
            $model->roles()->sync($roles, true);
240
        });
241
    }
242
243
    /**
244
     * {@inheritdoc}
245
     */
246
    protected static function boot()
247
    {
248
        parent::boot();
249
250
        static::saving(function (self $user) {
251
            foreach (array_intersect($user->getHashables(), array_keys($user->getAttributes())) as $hashable) {
252
                if ($user->isDirty($hashable) && Hash::needsRehash($user->{$hashable})) {
253
                    $user->{$hashable} = Hash::make($user->{$hashable});
254
                }
255
            }
256
        });
257
    }
258
259
    /**
260
     * The user may have many sessions.
261
     *
262
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
263
     */
264
    public function sessions(): MorphMany
265
    {
266
        return $this->morphMany(config('cortex.auth.models.session'), 'user');
267
    }
268
269
    /**
270
     * The user may have many socialites.
271
     *
272
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
273
     */
274
    public function socialites(): MorphMany
275
    {
276
        return $this->morphMany(config('cortex.auth.models.socialite'), 'user');
277
    }
278
279
    /**
280
     * Route notifications for the authy channel.
281
     *
282
     * @return int|null
283
     */
284
    public function routeNotificationForAuthy(): ?int
285
    {
286
        if (! ($authyId = array_get($this->getTwoFactor(), 'phone.authy_id')) && $this->getEmailForVerification() && $this->getPhoneForVerification() && $this->getCountryForVerification()) {
0 ignored issues
show
Bug introduced by
It seems like $this->getTwoFactor() targeting Rinvex\Auth\Traits\Authe...oFactor::getTwoFactor() can also be of type null; however, array_get() does only seem to accept object<ArrayAccess>|array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 190 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...
287
            $result = app('rinvex.authy.user')->register($this->getEmailForVerification(), preg_replace('/[^0-9]/', '', $this->getPhoneForVerification()), $this->getCountryForVerification());
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 191 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...
288
            $authyId = $result->get('user')['id'];
289
290
            // Prepare required variables
291
            $twoFactor = $this->getTwoFactor();
292
293
            // Update user account
294
            array_set($twoFactor, 'phone.authy_id', $authyId);
0 ignored issues
show
Bug introduced by
It seems like $twoFactor defined by $this->getTwoFactor() on line 291 can also be of type null; however, array_set() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
295
296
            $this->fill(['two_factor' => $twoFactor])->forceSave();
297
        }
298
299
        return $authyId;
300
    }
301
302
    /**
303
     * Get the user's country.
304
     *
305
     * @return \Rinvex\Country\Country
306
     */
307
    public function getCountryAttribute(): Country
308
    {
309
        return country($this->country_code);
310
    }
311
312
    /**
313
     * Get the user's language.
314
     *
315
     * @return \Rinvex\Language\Language
316
     */
317
    public function getLanguageAttribute(): Language
318
    {
319
        return language($this->language_code);
320
    }
321
322
    /**
323
     * Get full name attribute.
324
     *
325
     * @return string
326
     */
327
    public function getFullNameAttribute(): string
328
    {
329
        return implode(' ', [$this->given_name, $this->family_name]);
330
    }
331
332
    /**
333
     * Activate the user.
334
     *
335
     * @return $this
336
     */
337
    public function activate()
338
    {
339
        $this->update(['is_active' => true]);
340
341
        return $this;
342
    }
343
344
    /**
345
     * Deactivate the user.
346
     *
347
     * @return $this
348
     */
349
    public function deactivate()
350
    {
351
        $this->update(['is_active' => false]);
352
353
        return $this;
354
    }
355
356
    /**
357
     * Get the route key for the model.
358
     *
359
     * @return string
360
     */
361
    public function getRouteKeyName()
362
    {
363
        return 'username';
364
    }
365
}
366