Lae/app/Observers/UserObserver.php

85 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2023-02-12 16:02:45 +00:00
<?php
namespace App\Observers;
2023-02-23 01:53:45 +00:00
use App\Models\Affiliate\Affiliates;
2023-02-22 18:00:53 +00:00
use App\Models\Affiliate\AffiliateUser;
2023-02-12 16:02:45 +00:00
use App\Models\User;
2023-03-06 11:11:40 +00:00
use Faker\Provider\zh_CN\Person;
2023-03-06 11:18:11 +00:00
use Illuminate\Auth\Events\Registered;
2023-02-12 16:02:45 +00:00
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
2023-02-22 18:00:53 +00:00
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
2023-02-12 16:02:45 +00:00
class UserObserver
{
2023-02-22 18:00:53 +00:00
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
2023-02-12 16:02:45 +00:00
public function creating(User $user): void
{
2023-03-06 11:11:40 +00:00
if (! $user->name) {
$user->name = Person::firstNameMale();
}
2023-02-12 16:02:45 +00:00
$user->email_md5 = md5($user->email);
$user->uuid = Str::uuid();
2023-02-22 18:00:53 +00:00
// if session has affiliate_id, then set it to user
if (session()->has('affiliate_id')) {
2023-02-23 01:53:45 +00:00
$affiliate_id = session()->get('affiliate_id');
if (Affiliates::find($affiliate_id)) {
$user->affiliate_id = session()->get('affiliate_id');
}
2023-02-22 18:00:53 +00:00
}
}
public function created(User $user): void
{
// if user has affiliate_id, then create an affiliate_user record
if ($user->affiliate_id) {
AffiliateUser::create([
'affiliate_id' => $user->affiliate_id,
'user_id' => $user->id,
]);
}
2023-03-06 11:18:11 +00:00
event(new Registered($user));
2023-02-12 16:02:45 +00:00
}
public function updating(User $user): void
{
if ($user->isDirty('banned_at')) {
if ($user->banned_at) {
$user->tokens()->delete();
$user->hosts()->update(['status' => 'suspended', 'suspended_at' => now()]);
} else {
$user->hosts()->update(['status' => 'stopped']);
}
}
if ($user->isDirty('email')) {
$user->email_md5 = md5($user->email);
}
if ($user->isDirty('id_card') || $user->isDirty('real_name')) {
if (empty($user->id_card) || empty($user->real_name)) {
$user->real_name_verified_at = null;
} else {
$user->real_name_verified_at = now();
2023-02-13 07:14:30 +00:00
$user->id_card = Crypt::encryptString($user->id_card);
2023-02-13 07:16:06 +00:00
$user->birthday_at = $user->getBirthdayFromIdCard();
2023-02-12 16:02:45 +00:00
}
}
}
public function deleting(User $user): void
{
$user->tokens()->delete();
$user->hosts()->update(['status' => 'suspended', 'suspended_at' => now()]);
}
}