Completed
Push — develop ( 9481b1...1c9b89 )
by Abdelrahman
02:54
created

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