Files

71 lines
1.8 KiB
PHP

<?php
namespace App\Features\Scraper\Services;
use App\Features\Consoles\Models\Console;
use App\Features\Games\Models\Game;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
class ScraperService
{
public function __construct(
private IGDBCoverScraper $igdb,
private TGDBCoverScraper $tgdb
) {}
public function search(string $query, ?string $consoleSlug = null): Collection
{
$console = $consoleSlug
? Console::where('slug', $consoleSlug)->first()
: null;
$consoleId = $console?->igdb_platform_id;
$results = $this->igdb->search($query, $consoleId);
if ($results->isEmpty()) {
$tgdbConsoleId = $console?->tgdb_platform_id;
$results = $this->tgdb->search($query, $tgdbConsoleId);
}
return $results;
}
public function scrapeForGame(Game $game): ?string
{
$coverUrl = null;
if ($game->igdb_id) {
$coverUrl = $this->igdb->getCoverUrl($game->igdb_id);
}
if (! $coverUrl && $game->tgdb_id) {
$coverUrl = $this->tgdb->getCoverUrl($game->tgdb_id);
}
if ($coverUrl) {
return $this->downloadCover($coverUrl, $game);
}
return null;
}
public function downloadCover(string $url, Game $game): string
{
$consoleSlug = $game->console->slug ?? 'unknown';
$filename = "{$game->slug}-cover.jpg";
$path = "covers/{$consoleSlug}/{$filename}";
try {
$contents = Http::timeout(30)->get($url)->body();
Storage::disk('local')->put($path, $contents);
return $path;
} catch (\Exception $e) {
return '';
}
}
}