Completed
Push — develop ( cfe930...cce307 )
by Abdelrahman
01:51
created

User::getRouteKeyName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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