Files
SkinbaseNova/app/Observers/ArtworkFavouriteObserver.php
2026-02-26 21:12:32 +01:00

46 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\ArtworkFavourite;
use App\Services\UserStatsService;
use Illuminate\Support\Facades\DB;
/**
* Updates the artwork creator's favorites_received_count and last_active_at
* whenever a favourite is added or removed.
*/
class ArtworkFavouriteObserver
{
public function __construct(
private readonly UserStatsService $userStats,
) {}
public function created(ArtworkFavourite $favourite): void
{
$creatorId = $this->creatorId($favourite->artwork_id);
if ($creatorId) {
$this->userStats->incrementFavoritesReceived($creatorId);
}
}
public function deleted(ArtworkFavourite $favourite): void
{
$creatorId = $this->creatorId($favourite->artwork_id);
if ($creatorId) {
$this->userStats->decrementFavoritesReceived($creatorId);
}
}
private function creatorId(int $artworkId): ?int
{
$id = DB::table('artworks')
->where('id', $artworkId)
->value('user_id');
return $id !== null ? (int) $id : null;
}
}