64 lines
1.5 KiB
PHP
64 lines
1.5 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Observers;
|
||
|
||
use App\Models\ArtworkAward;
|
||
use App\Services\ArtworkAwardService;
|
||
use App\Services\UserStatsService;
|
||
use Illuminate\Support\Facades\DB;
|
||
|
||
class ArtworkAwardObserver
|
||
{
|
||
public function __construct(
|
||
private readonly ArtworkAwardService $service,
|
||
private readonly UserStatsService $userStats,
|
||
) {}
|
||
|
||
public function created(ArtworkAward $award): void
|
||
{
|
||
$this->refresh($award);
|
||
$this->trackCreatorStats($award, +1);
|
||
}
|
||
|
||
public function updated(ArtworkAward $award): void
|
||
{
|
||
$this->refresh($award);
|
||
// Medal changed – count stays the same; no stat change needed.
|
||
}
|
||
|
||
public function deleted(ArtworkAward $award): void
|
||
{
|
||
$this->refresh($award);
|
||
$this->trackCreatorStats($award, -1);
|
||
}
|
||
|
||
private function refresh(ArtworkAward $award): void
|
||
{
|
||
$this->service->recalcStats($award->artwork_id);
|
||
|
||
$artwork = $award->artwork;
|
||
if ($artwork) {
|
||
$this->service->syncToSearch($artwork);
|
||
}
|
||
}
|
||
|
||
private function trackCreatorStats(ArtworkAward $award, int $delta): void
|
||
{
|
||
$creatorId = DB::table('artworks')
|
||
->where('id', $award->artwork_id)
|
||
->value('user_id');
|
||
|
||
if (! $creatorId) {
|
||
return;
|
||
}
|
||
|
||
if ($delta > 0) {
|
||
$this->userStats->incrementAwardsReceived((int) $creatorId);
|
||
} else {
|
||
$this->userStats->decrementAwardsReceived((int) $creatorId);
|
||
}
|
||
}
|
||
}
|