Lae/app/Models/User.php

81 lines
1.9 KiB
PHP
Raw Normal View History

2022-08-12 07:56:56 +00:00
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
2022-08-30 09:20:45 +00:00
use Laravel\Sanctum\HasApiTokens;
use App\Exceptions\CommonException;
use App\Exceptions\User\BalanceNotEnoughException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Cache\LockTimeoutException;
2022-08-12 07:56:56 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
2022-08-30 09:20:45 +00:00
'balance' => 'float',
2022-08-12 07:56:56 +00:00
];
2022-08-30 09:20:45 +00:00
public function toDrops($amount = 1)
{
$rate = Cache::get('drops_rate', 100);
$total = $amount * $rate;
$cache_key = 'user_drops_' . $this->id;
$lock = Cache::lock("lock_" . $cache_key, 5);
try {
$lock->block(5);
$this->balance -= $amount;
$this->save();
// increment user drops
Cache::increment($cache_key, $total);
2022-09-03 17:19:41 +00:00
// if user balance <= 0
if ($this->balance < $amount) {
throw new BalanceNotEnoughException('余额不足');
}
2022-08-30 09:20:45 +00:00
} catch (LockTimeoutException) {
throw new CommonException('暂时无法处理此请求,请稍后再试。');
} finally {
optional($lock)->release();
}
return $this;
}
2022-08-12 07:56:56 +00:00
}