52 lines
1.7 KiB
PHP
52 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Actions\Fortify;
|
|
|
|
use App\Enums\UserType;
|
|
use App\Models\User;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
use Laravel\Fortify\Contracts\CreatesNewUsers;
|
|
|
|
class CreateNewUser implements CreatesNewUsers
|
|
{
|
|
use PasswordValidationRules;
|
|
|
|
|
|
/**
|
|
* Validate and create a newly registered user.
|
|
*
|
|
* @param array{username: string, email: string, password: string, type: string} $userInfos An associative array containing user information.
|
|
*
|
|
* @throws Exception
|
|
* @noinspection PhpParameterNameChangedDuringInheritanceInspection
|
|
*/
|
|
public function create(array $userInfos): User|Exception
|
|
{
|
|
try {
|
|
Validator::make($userInfos, [
|
|
'username' => ['required', 'string', 'max:255', Rule::unique(User::class, 'login')],
|
|
'password' => $this->passwordRules(),
|
|
'email' => ['required', 'string', 'max:255', Rule::unique(User::class, 'email')],
|
|
'type' => ['required', 'string', 'max:6', Rule::in(['admin', 'editor', 'dj'])],
|
|
])->validate();
|
|
} catch (Exception $e) {
|
|
throw new Exception($e->getMessage(), $e->getCode(), $e);
|
|
}
|
|
|
|
try {
|
|
$user = User::create([
|
|
'login' => $userInfos['username'],
|
|
'pass' => Hash::make($userInfos['password']),
|
|
'email' => $userInfos['email'],
|
|
'type' => UserType::from($userInfos['type'])->name,
|
|
]);
|
|
$user->assignRole($userInfos['type']);
|
|
return $user;
|
|
} catch (Exception $e) {
|
|
throw new Exception($e->getMessage(), $e->getCode(), $e);
|
|
}
|
|
}
|
|
}
|