Completed
Push — master ( f2b66c...15eb15 )
by Abdelrahman
11:47 queued 10:02
created

User::__call()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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