2022-06-10 10:47:46 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2023-08-20 22:35:58 +00:00
|
|
|
use App\Exceptions\UserProspectUpdateDeniedException;
|
2022-06-10 10:47:46 +00:00
|
|
|
use App\Models\User;
|
|
|
|
use Illuminate\Contracts\Hashing\Hasher;
|
2024-03-19 22:48:12 +00:00
|
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
use Illuminate\Support\Str;
|
2022-06-10 10:47:46 +00:00
|
|
|
|
|
|
|
class UserService
|
|
|
|
{
|
2024-03-19 22:48:12 +00:00
|
|
|
public function __construct(private Hasher $hash, private ImageWriter $imageWriter)
|
2022-06-10 10:47:46 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public function createUser(string $name, string $email, string $plainTextPassword, bool $isAdmin): User
|
|
|
|
{
|
2022-08-09 18:45:11 +00:00
|
|
|
return User::query()->create([
|
2022-06-10 10:47:46 +00:00
|
|
|
'name' => $name,
|
|
|
|
'email' => $email,
|
|
|
|
'password' => $this->hash->make($plainTextPassword),
|
|
|
|
'is_admin' => $isAdmin,
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2024-03-19 22:48:12 +00:00
|
|
|
public function updateUser(
|
|
|
|
User $user,
|
|
|
|
string $name,
|
|
|
|
string $email,
|
|
|
|
?string $password,
|
|
|
|
?bool $isAdmin = null,
|
|
|
|
?string $avatar = null
|
|
|
|
): User {
|
2023-08-20 22:35:58 +00:00
|
|
|
throw_if($user->is_prospect, new UserProspectUpdateDeniedException());
|
|
|
|
|
2022-07-29 06:47:10 +00:00
|
|
|
$data = [
|
2022-06-10 10:47:46 +00:00
|
|
|
'name' => $name,
|
|
|
|
'email' => $email,
|
2022-07-29 06:47:10 +00:00
|
|
|
];
|
|
|
|
|
2024-03-19 22:48:12 +00:00
|
|
|
if ($isAdmin !== null) {
|
|
|
|
$data['is_admin'] = $isAdmin;
|
|
|
|
}
|
|
|
|
|
2022-07-29 06:47:10 +00:00
|
|
|
if ($password) {
|
|
|
|
$data['password'] = $this->hash->make($password);
|
|
|
|
}
|
|
|
|
|
2024-03-19 22:48:12 +00:00
|
|
|
if ($avatar) {
|
|
|
|
$oldAvatar = $user->getRawOriginal('avatar');
|
|
|
|
|
|
|
|
$path = self::generateUserAvatarPath();
|
|
|
|
$this->imageWriter->write($path, $avatar, ['max_width' => 480]);
|
|
|
|
$data['avatar'] = basename($path);
|
|
|
|
|
|
|
|
if ($oldAvatar) {
|
|
|
|
File::delete($oldAvatar);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
$data['avatar'] = null;
|
|
|
|
}
|
|
|
|
|
2022-07-29 06:47:10 +00:00
|
|
|
$user->update($data);
|
2022-06-10 10:47:46 +00:00
|
|
|
|
|
|
|
return $user;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function deleteUser(User $user): void
|
|
|
|
{
|
|
|
|
$user->delete();
|
|
|
|
}
|
2024-01-23 22:50:50 +00:00
|
|
|
|
|
|
|
public function savePreference(User $user, string $key, mixed $value): void
|
|
|
|
{
|
|
|
|
$user->preferences = $user->preferences->set($key, $value);
|
|
|
|
|
|
|
|
$user->save();
|
|
|
|
}
|
2024-03-19 22:48:12 +00:00
|
|
|
|
|
|
|
private static function generateUserAvatarPath(): string
|
|
|
|
{
|
|
|
|
return user_avatar_path(sprintf('%s.webp', sha1(Str::uuid())));
|
|
|
|
}
|
2022-06-10 10:47:46 +00:00
|
|
|
}
|