Lae/app/Observers/HostObserver.php

109 lines
2.5 KiB
PHP
Raw Permalink Normal View History

2023-02-12 16:02:45 +00:00
<?php
namespace App\Observers;
use App\Events\Users;
use App\Jobs\Host\HostJob;
use App\Models\Host;
use App\Notifications\WebNotification;
2023-03-02 04:30:54 +00:00
use Illuminate\Support\Facades\Cache;
2023-02-12 16:02:45 +00:00
class HostObserver
{
public function creating(Host $host): void
{
$host->hour_at = now()->hour;
$host->minute_at = now()->minute;
2023-03-07 16:45:29 +00:00
$host->day_at = now()->day;
2023-02-12 16:02:45 +00:00
if ($host->price !== null) {
$host->price = bcdiv($host->price, 1, 2);
}
if ($host->managed_price !== null) {
$host->managed_price = bcdiv($host->managed_price, 1, 2);
}
2023-03-07 16:45:29 +00:00
if (! $host->billing_cycle) {
$host->billing_cycle = 'hourly';
}
2023-02-12 16:02:45 +00:00
}
/**
* Handle the Host "created" event.
*/
public function created(Host $host): void
{
$host->load('module');
// model price 使用 bcmul 保留两位小数
$host->price = bcmul($host->price, 1, 2);
$host->user->notify(new WebNotification($host, 'hosts.created'));
2023-02-13 09:05:41 +00:00
$host->save();
2023-03-07 16:45:29 +00:00
if ($host->isMonthly()) {
$host->cost(null, true, '预');
}
2023-02-12 16:02:45 +00:00
}
/**
* Handle the Host "updated" event.
*/
2023-03-02 04:30:54 +00:00
public function updating(Host $host): bool
2023-02-12 16:02:45 +00:00
{
2023-03-02 04:30:54 +00:00
// 取得锁
$lock = Cache::lock('host:updating:'.$host->id, 10);
if (! $lock->get()) {
return false;
}
2023-02-12 16:02:45 +00:00
if ($host->isDirty('status')) {
if ($host->status == 'suspended') {
$host->suspended_at = now();
} else {
$host->suspended_at = null;
}
if ($host->status == 'locked') {
$host->locked_at = now();
} else {
$host->locked_at = null;
}
if ($host->status == 'unavailable') {
$host->unavailable_at = now();
} else {
$host->unavailable_at = null;
}
}
// 调度任务
if ($host->status !== 'unavailable') {
dispatch(new HostJob($host, 'patch'));
}
broadcast(new Users($host->user_id, 'hosts.updating', $host));
2023-03-02 04:30:54 +00:00
// 释放锁
$lock->release();
return true;
2023-02-12 16:02:45 +00:00
}
public function updated(Host $host): void
{
broadcast(new Users($host->user_id, 'hosts.updated', $host));
}
/**
* Handle the Host "deleted" event.
*/
public function deleted(Host $host): void
{
broadcast(new Users($host->user_id, 'hosts.deleted', $host));
}
}