Completed
Push — develop ( 7021c4...3ebefa )
by Abdelrahman
01:56
created

User::makeActive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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