Completed
Push — develop ( bd4be1...49447a )
by Abdelrahman
21:59
created

User   C

Complexity

Total Complexity 22

Size/Duplication

Total Lines 330
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 20

Importance

Changes 0
Metric Value
wmc 22
lcom 2
cbo 20
dl 0
loc 330
rs 6.4705
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A registerMediaCollections() 0 5 1
A setAbilitiesAttribute() 0 14 2
A setRolesAttribute() 0 14 2
A boot() 0 12 4
A sessions() 0 4 1
A socialites() 0 4 1
B routeNotificationForAuthy() 0 17 5
A getCountryAttribute() 0 4 1
A getLanguageAttribute() 0 4 1
A getFullNameAttribute() 0 4 1
A makeActive() 0 6 1
A makeInactive() 0 6 1
A getRouteKeyName() 0 4 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\Attributes\Traits\Attributable;
22
use Rinvex\Support\Traits\ValidatingTrait;
23
use Spatie\Activitylog\Traits\HasActivity;
24
use Spatie\MediaLibrary\HasMedia\HasMedia;
25
use Rinvex\Support\Traits\HasSocialAttributes;
26
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
27
use Rinvex\Auth\Traits\AuthenticatableTwoFactor;
28
use Rinvex\Auth\Contracts\CanVerifyEmailContract;
29
use Rinvex\Auth\Contracts\CanVerifyPhoneContract;
30
use Silber\Bouncer\Database\HasRolesAndAbilities;
31
use Illuminate\Foundation\Auth\Access\Authorizable;
32
use Rinvex\Auth\Contracts\CanResetPasswordContract;
33
use Illuminate\Database\Eloquent\Relations\MorphMany;
34
use Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract;
35
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
36
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
37
38
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...
39
{
40
    // @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...
41
    // Duplicate trait usage to fire attached events for cache
42
    // flush before other events in other traits specially HasActivity,
43
    // otherwise old cached queries used and no changelog recorded on update.
44
    use CacheableEloquent;
45
    use Taggable;
46
    use Auditable;
47
    use Notifiable;
48
    use HasActivity;
49
    use HashidsTrait;
50
    use Attributable;
51
    use Authorizable;
52
    use HasHashables;
53
    use HasMediaTrait;
54
    use CanVerifyEmail;
55
    use CanVerifyPhone;
56
    use Authenticatable;
57
    use ValidatingTrait;
58
    use CanResetPassword;
59
    use HasSocialAttributes;
60
    use HasRolesAndAbilities;
61
    use AuthenticatableTwoFactor;
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected $fillable = [
67
        'username',
68
        'password',
69
        'two_factor',
70
        'email',
71
        'email_verified',
72
        'email_verified_at',
73
        'phone',
74
        'phone_verified',
75
        'phone_verified_at',
76
        'given_name',
77
        'family_name',
78
        'title',
79
        'organization',
80
        'country_code',
81
        'language_code',
82
        'birthday',
83
        'gender',
84
        'social',
85
        'is_active',
86
        'last_activity',
87
        'abilities',
88
        'roles',
89
        'tags',
90
    ];
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    protected $casts = [
96
        'username' => 'string',
97
        'password' => 'string',
98
        'two_factor' => 'json',
99
        'email' => 'string',
100
        'email_verified' => 'boolean',
101
        'email_verified_at' => 'datetime',
102
        'phone' => 'string',
103
        'phone_verified' => 'boolean',
104
        'phone_verified_at' => 'datetime',
105
        'given_name' => 'string',
106
        'family_name' => 'string',
107
        'title' => 'string',
108
        'organization' => 'string',
109
        'country_code' => 'string',
110
        'language_code' => 'string',
111
        'birthday' => 'string',
112
        'gender' => 'string',
113
        'social' => 'array',
114
        'is_active' => 'boolean',
115
        'last_activity' => 'datetime',
116
        'deleted_at' => 'datetime',
117
    ];
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    protected $hidden = [
123
        'password',
124
        'two_factor',
125
        'remember_token',
126
    ];
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    protected $observables = [
132
        'validating',
133
        'validated',
134
    ];
135
136
    /**
137
     * The attributes to be encrypted before saving.
138
     *
139
     * @var array
140
     */
141
    protected $hashables = [
142
        'password',
143
    ];
144
145
    /**
146
     * The default rules that the model will validate against.
147
     *
148
     * @var array
149
     */
150
    protected $rules = [];
151
152
    /**
153
     * Whether the model should throw a
154
     * ValidationException if it fails validation.
155
     *
156
     * @var bool
157
     */
158
    protected $throwValidationExceptions = true;
159
160
    /**
161
     * Indicates whether to log only dirty attributes or all.
162
     *
163
     * @var bool
164
     */
165
    protected static $logOnlyDirty = true;
166
167
    /**
168
     * The attributes that are logged on change.
169
     *
170
     * @var array
171
     */
172
    protected static $logFillable = true;
173
174
    /**
175
     * The attributes that are ignored on change.
176
     *
177
     * @var array
178
     */
179
    protected static $ignoreChangedAttributes = [
180
        'password',
181
        'two_factor',
182
        'email_verified_at',
183
        'phone_verified_at',
184
        'last_activity',
185
        'created_at',
186
        'updated_at',
187
        'deleted_at',
188
    ];
189
190
    /**
191
     * Register media collections.
192
     *
193
     * @return void
194
     */
195
    public function registerMediaCollections(): void
196
    {
197
        $this->addMediaCollection('profile_picture')->singleFile();
198
        $this->addMediaCollection('cover_photo')->singleFile();
199
    }
200
201
    /**
202
     * Attach the given abilities to the model.
203
     *
204
     * @param mixed $abilities
205
     *
206
     * @return void
207
     */
208
    public function setAbilitiesAttribute($abilities): void
209
    {
210
        static::saved(function (self $model) use ($abilities) {
211
            $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...
212
213
            $model->abilities->pluck('id')->similar($abilities)
214
            || activity()
215
                ->performedOn($model)
216
                ->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...
217
                ->log('updated');
218
219
            $model->abilities()->sync($abilities, true);
220
        });
221
    }
222
223
    /**
224
     * Attach the given roles to the model.
225
     *
226
     * @param mixed $roles
227
     *
228
     * @return void
229
     */
230
    public function setRolesAttribute($roles): void
231
    {
232
        static::saved(function (self $model) use ($roles) {
233
            $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...
234
235
            $model->roles->pluck('id')->similar($roles)
236
            || activity()
237
                ->performedOn($model)
238
                ->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...
239
                ->log('updated');
240
241
            $model->roles()->sync($roles, true);
242
        });
243
    }
244
245
    /**
246
     * {@inheritdoc}
247
     */
248
    protected static function boot()
249
    {
250
        parent::boot();
251
252
        static::saving(function (self $user) {
253
            foreach (array_intersect($user->getHashables(), array_keys($user->getAttributes())) as $hashable) {
254
                if ($user->isDirty($hashable) && Hash::needsRehash($user->$hashable)) {
255
                    $user->$hashable = Hash::make($user->$hashable);
256
                }
257
            }
258
        });
259
    }
260
261
    /**
262
     * The user may have many sessions.
263
     *
264
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
265
     */
266
    public function sessions(): MorphMany
267
    {
268
        return $this->morphMany(config('cortex.auth.models.session'), 'user');
269
    }
270
271
    /**
272
     * The user may have many socialites.
273
     *
274
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
275
     */
276
    public function socialites(): MorphMany
277
    {
278
        return $this->morphMany(config('cortex.auth.models.socialite'), 'user');
279
    }
280
281
    /**
282
     * Route notifications for the authy channel.
283
     *
284
     * @return int|null
285
     */
286
    public function routeNotificationForAuthy(): ?int
287
    {
288
        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...
289
            $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...
290
            $authyId = $result->get('user')['id'];
291
292
            // Prepare required variables
293
            $twoFactor = $this->getTwoFactor();
294
295
            // Update user account
296
            array_set($twoFactor, 'phone.authy_id', $authyId);
0 ignored issues
show
Bug introduced by
It seems like $twoFactor defined by $this->getTwoFactor() on line 293 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...
297
298
            $this->fill(['two_factor' => $twoFactor])->forceSave();
299
        }
300
301
        return $authyId;
302
    }
303
304
    /**
305
     * Get the user's country.
306
     *
307
     * @return \Rinvex\Country\Country
308
     */
309
    public function getCountryAttribute(): Country
310
    {
311
        return country($this->country_code);
312
    }
313
314
    /**
315
     * Get the user's language.
316
     *
317
     * @return \Rinvex\Language\Language
318
     */
319
    public function getLanguageAttribute(): Language
320
    {
321
        return language($this->language_code);
322
    }
323
324
    /**
325
     * Get full name attribute.
326
     *
327
     * @return string
328
     */
329
    public function getFullNameAttribute(): string
330
    {
331
        return implode(' ', [$this->given_name, $this->family_name]);
332
    }
333
334
    /**
335
     * Activate the user.
336
     *
337
     * @return $this
338
     */
339
    public function makeActive()
340
    {
341
        $this->update(['is_active' => true]);
342
343
        return $this;
344
    }
345
346
    /**
347
     * Deactivate the user.
348
     *
349
     * @return $this
350
     */
351
    public function makeInactive()
352
    {
353
        $this->update(['is_active' => false]);
354
355
        return $this;
356
    }
357
358
    /**
359
     * Get the route key for the model.
360
     *
361
     * @return string
362
     */
363
    public function getRouteKeyName()
364
    {
365
        return 'username';
366
    }
367
}
368