2024-08-30 01:28:17 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use App\Models\User;
|
|
|
|
use Illuminate\Http\Exceptions\HttpResponseException;
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
use Illuminate\Support\Facades\Hash;
|
|
|
|
|
|
|
|
class UserService
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Create(register) new user
|
|
|
|
* @param array $data This is expected to be validated already
|
|
|
|
* @return User
|
|
|
|
*/
|
|
|
|
public function create($data, $autoLogin = true): User
|
|
|
|
{
|
|
|
|
if (User::where([ 'email' => $data['email'] ])->count() !== 0) {
|
|
|
|
throw new HttpResponseException(response()->json('email_taken', 400));
|
|
|
|
}
|
|
|
|
|
|
|
|
$data['password'] = Hash::make($data['password']);
|
|
|
|
|
|
|
|
$user = User::create($data);
|
|
|
|
if ($autoLogin) {
|
|
|
|
Auth::login($user);
|
|
|
|
}
|
|
|
|
return $user;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Login to user
|
|
|
|
* @param array $data This is expected to be validated already
|
|
|
|
* @return User
|
|
|
|
*/
|
|
|
|
public function login($data): bool
|
|
|
|
{
|
|
|
|
if (Auth::attempt($data)) {
|
|
|
|
request()->session()->regenerate();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-08-30 03:31:22 +02:00
|
|
|
public function setPassword($data)
|
2024-08-30 01:28:17 +02:00
|
|
|
{
|
|
|
|
$user = User::where([ 'email' => $data['email'] ])->first();
|
|
|
|
if ($user === null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$user->password = Hash::make($data['password']);
|
|
|
|
$user->save();
|
|
|
|
}
|
2024-08-30 02:17:13 +02:00
|
|
|
|
|
|
|
public function listAll(): array
|
|
|
|
{
|
|
|
|
return User::all()->toArray();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getOneById(string $id): User | null
|
|
|
|
{
|
|
|
|
return User::where([ 'id' => $id ])->first();
|
|
|
|
}
|
2024-08-30 03:31:22 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Will return `null` if failed
|
|
|
|
*/
|
|
|
|
public function editUser(array $data, string $id): User | null
|
|
|
|
{
|
|
|
|
$user = $this->getOneById($id);
|
|
|
|
if ($user === null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (array_key_exists('password', $data)) {
|
|
|
|
$this->setPassword([ 'email' => $user['email'], 'password' => $data['password'] ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
$user->fill($data['user']);
|
|
|
|
$user->save();
|
|
|
|
return $user;
|
|
|
|
}
|
2024-08-30 06:16:16 +02:00
|
|
|
|
|
|
|
public function getUnexistingIds(array $ids): null | array
|
|
|
|
{
|
|
|
|
$users = User::whereIn('id', $ids)->get();
|
|
|
|
if ($users->count() != count($ids)) {
|
|
|
|
$existingIds = $users->map(
|
|
|
|
function($model) {
|
|
|
|
return $model->id;
|
|
|
|
}
|
|
|
|
)->toArray();
|
|
|
|
return array_diff($ids, $existingIds);
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
2024-08-30 01:28:17 +02:00
|
|
|
}
|