ldc-bogt/app/Models/User.php

116 lines
3.1 KiB
PHP
Raw Normal View History

2019-12-04 17:30:46 +01:00
<?php
2022-03-08 11:49:18 +01:00
namespace App\Models;
2019-12-04 17:30:46 +01:00
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
2022-03-08 11:49:18 +01:00
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
2019-12-04 17:30:46 +01:00
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
2022-03-08 11:49:18 +01:00
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (User $user) {
static::assertUsernameIsUnique($user->id, $user->username);
static::assertEmailIsUnique($user->id, $user->email);
if (Hash::needsRehash($user->password)) {
$user->password = Hash::make($user->password);
}
$user->remember_token = Str::random(10);
});
static::updating(function (User $user) {
static::assertUsernameIsUnique($user->id, $user->username);
static::assertEmailIsUnique($user->id, $user->email);
if (Hash::needsRehash($user->password)) {
$user->password = Hash::make($user->password);
}
$user->remember_token = Str::random(10);
});
}
/**
* Asserts using validation that the email is unique
*
* @param mixed $id
* @param mixed $email
* @return void
* @throws \Illuminate\Validation\ValidationException If user email as already used.
*/
private static function assertEmailIsUnique($id, $email)
{
self::assertFieldIsUnique($id, 'email', $email);
}
/**
* Asserts using validation that the login is unique
*
* @param mixed $id
* @param mixed $login
* @return void
* @throws \Illuminate\Validation\ValidationException If user login as already used.
*/
private static function assertUsernameIsUnique($id, $login)
{
self::assertFieldIsUnique($id, 'username', $login);
}
/**
* Asserts that the field is unique
*
* @param mixed $id
* @param string $field
* @param mixed $value
* @return void
* @throws \Illuminate\Validation\ValidationException If the field is not unique.
*/
private static function assertFieldIsUnique($id, string $field, $value)
{
Validator::make([$field => $value], [
$field => Rule::unique('users', $field)->ignore($id),
], [
$field . '.unique' => trans('La valeur :value pour le champ :attribute est déjà utilisé', [
'attribute' => $field,
'value' => $value
])
])->validate();
}
2019-12-04 17:30:46 +01:00
}