first commit

This commit is contained in:
2025-04-09 23:03:16 +03:00
commit 909d514552
129 changed files with 17249 additions and 0 deletions
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Console\Commands;
use App\Services\IgdbService;
use Illuminate\Console\Command;
use MarcReichel\IGDBLaravel\Models\Game;
class BuildGameLibrary extends Command
{
protected $signature = 'igdb:build-library
{--limit=100 : Number of games to fetch per batch}
{--batches=10 : Number of batches to process}
{--start-year=1980 : Start year for game releases}
{--end-year=2024 : End year for game releases}';
protected $description = 'Build a comprehensive game library by fetching games in batches';
public function handle(IgdbService $igdbService): int
{
$limit = (int) $this->option('limit');
$batches = (int) $this->option('batches');
$startYear = (int) $this->option('start-year');
$endYear = (int) $this->option('end-year');
$this->info("Starting to build game library...");
$this->info("Will fetch {$limit} games per batch for {$batches} batches");
$this->info("Covering games released between {$startYear} and {$endYear}");
$totalProcessed = 0;
$totalAdded = 0;
$totalSkipped = 0;
for ($batch = 1; $batch <= $batches; $batch++) {
$this->newLine();
$this->info("Processing batch {$batch} of {$batches}");
// Generate a random year within our range
$year = rand($startYear, $endYear);
$startTimestamp = strtotime("{$year}-01-01");
$endTimestamp = strtotime("{$year}-12-31");
// Generate a random query to get diverse results
$query = $this->generateRandomQuery();
$this->info("Searching for games from {$year} with query: {$query}");
$games = $igdbService->get();
if (empty($games)) {
$this->warn("No games found for this batch. Moving to next batch...");
continue;
}
$this->info(sprintf('Found %d games. Processing...', count($games)));
$bar = $this->output->createProgressBar(count($games));
$bar->start();
/** @var Game $gameData */
foreach ($games as $gameData) {
$totalProcessed++;
try {
$igdbService->processGameData($gameData);
$totalAdded++;
} catch (\Exception $e) {
$this->warn("\nFailed to process game: {$e->getMessage()}");
$totalSkipped++;
}
$bar->advance();
}
$bar->finish();
// Add a small delay between batches to avoid rate limiting
if ($batch < $batches) {
$this->info("\nWaiting 2 seconds before next batch...");
sleep(2);
}
}
$this->newLine(2);
$this->info("Library building complete!");
$this->info("Total games processed: {$totalProcessed}");
$this->info("New games added: {$totalAdded}");
$this->info("Games skipped (invalid data): {$totalSkipped}");
return 0;
}
protected function generateRandomQuery(): string
{
$prefixes = ['', 'the ', 'super ', 'mega ', 'ultimate '];
$suffixes = ['', ' game', ' edition', ' deluxe', ' special'];
$words = ['action', 'adventure', 'rpg', 'strategy', 'shooter', 'platformer',
'racing', 'sports', 'fighting', 'puzzle', 'simulation', 'horror'];
$prefix = $prefixes[array_rand($prefixes)];
$word = $words[array_rand($words)];
$suffix = $suffixes[array_rand($suffixes)];
return $prefix . $word . $suffix;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Models\Game;
use App\Services\IgdbService;
use Illuminate\Console\Command;
class FetchIgdbGames extends Command
{
protected $signature = 'igdb:fetch {query?} {--limit=10}';
protected $description = 'Fetch games from IGDB and store them in the database';
public function handle(IgdbService $igdbService): int
{
$query = $this->argument('query') ?? $this->ask('Enter search query');
$limit = (int) $this->option('limit');
$this->info("Fetching games for query: {$query}");
$games = $igdbService->searchGames($query, $limit);
if (empty($games)) {
$this->error('No games found or an error occurred.');
return 1;
}
$this->info(sprintf('Found %d games. Processing...', count($games)));
$bar = $this->output->createProgressBar(count($games));
$bar->start();
foreach ($games as $gameData) {
$this->processGame($gameData);
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info('Done!');
return 0;
}
protected function processGame(array $gameData): void
{
$game = Game::updateOrCreate(
['igdb_id' => $gameData['id']],
[
'name' => $gameData['name'],
'summary' => $gameData['summary'] ?? null,
'cover_url' => $gameData['cover']['url'] ?? null,
'slug' => $gameData['slug'] ?? null,
'genres' => array_column($gameData['genres'] ?? [], 'name'),
'platforms' => array_column($gameData['platforms'] ?? [], 'name'),
'first_release_date' => isset($gameData['first_release_date'])
? date('Y-m-d', $gameData['first_release_date'])
: null,
'rating' => $gameData['rating'] ?? null,
'rating_count' => $gameData['rating_count'] ?? null,
]
);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*/
public function show(): View
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('dashboard', absolute: false));
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*/
public function __invoke(Request $request): RedirectResponse|View
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('dashboard', absolute: false))
: view('auth.verify-email');
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*/
public function create(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class PasswordController extends Controller
{
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validateWithBag('updatePassword', [
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('status', 'password-updated');
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\View\View;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*/
public function create(): View
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers;
use App\Models\Game;
use Illuminate\Http\Request;
class GameController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'igdb_id' => 'required|integer|unique:games',
'name' => 'required|string|max:255',
'summary' => 'nullable|string',
'storyline' => 'nullable|string',
'cover_url' => 'nullable|url',
'slug' => 'required|string|max:255|unique:games',
'first_release_date' => 'nullable|date',
'rating' => 'nullable|numeric|between:0,100',
'rating_count' => 'nullable|integer|min:0',
'category' => 'nullable|integer',
'status' => 'nullable|integer',
'url' => 'nullable|url',
'version_title' => 'nullable|string|max:255',
]);
$game = Game::create($validated);
return response()->json($game, 201);
}
}
@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): View
{
return view('profile.edit', [
'user' => $request->user(),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Artwork extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'game_id',
'url',
'width',
'height',
'image_id',
];
public function game(): BelongsTo
{
return $this->belongsTo(Game::class);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Game extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'name',
'summary',
'storyline',
'cover_url',
'slug',
'first_release_date',
'rating',
'rating_count',
'category',
'status',
'url',
'version_title',
];
protected $casts = [
'first_release_date' => 'date',
'rating' => 'float',
'rating_count' => 'integer',
];
public function genres(): BelongsToMany
{
return $this->belongsToMany(Genre::class);
}
public function platforms(): BelongsToMany
{
return $this->belongsToMany(Platform::class);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Genre extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'name',
'slug',
];
public function games(): BelongsToMany
{
return $this->belongsToMany(Game::class);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Platform extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'name',
'slug',
'abbreviation',
];
public function games(): BelongsToMany
{
return $this->belongsToMany(Game::class);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Screenshot extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'game_id',
'url',
'width',
'height',
'image_id',
];
public function game(): BelongsTo
{
return $this->belongsTo(Game::class);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Video extends Model
{
use HasFactory;
protected $fillable = [
'igdb_id',
'game_id',
'name',
'video_id',
'url',
'checksum',
];
public function game(): BelongsTo
{
return $this->belongsTo(Game::class);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
+346
View File
@@ -0,0 +1,346 @@
<?php
namespace App\Services;
use App\Models\Game;
use App\Models\Genre;
use App\Models\Platform;
use App\Models\Artwork;
use App\Models\Screenshot;
use App\Models\Video;
use Illuminate\Support\Facades\Log;
use MarcReichel\IGDBLaravel\Models\Collection;
use MarcReichel\IGDBLaravel\Models\Game as IgdbGame;
use MarcReichel\IGDBLaravel\Models\Cover;
use MarcReichel\IGDBLaravel\Models\Genre as IgdbGenre;
use MarcReichel\IGDBLaravel\Models\Platform as IgdbPlatform;
class IgdbService
{
public function get()
{
try {
$existingIds = $this->getExistingIds();
$queryBuilder = IgdbGame::select([
'id',
'name',
'summary',
'cover.url',
'slug',
'genres',
'platforms',
'first_release_date',
'rating',
'rating_count'
])
->where('rating_count', '>', 0)
->where('category', '=', 0);
if (!empty($existingIds)) {
$queryBuilder = $queryBuilder->whereNotIn('id', array_map(function($id) {
return (int)str_replace('"', '', $id);
}, $existingIds));
}
$a = $queryBuilder
->limit(50)
->get();
}catch (\Throwable $e) {
dd(
$e->getMessage(),
$e->getTrace()
);
}
return $a;
}
private function getExistingIds(): ?array
{
$existingGames = Game::get();
if (empty($existingGames)) {
return null;
}
$existingIds = [];
/** @var Game $existingGame */
foreach ($existingGames as $existingGame) {
$existingIds[] = (string)$existingGame->id;
}
return array_map(function($id) {
return '"'.$id.'"';
}, $existingIds);
}
public function searchGames(string $query, int $limit = 10, ?int $startTimestamp = null, ?int $endTimestamp = null): array
{
try {
$queryBuilder = IgdbGame::select([
'id',
'name',
'summary',
'cover',
'slug',
'genres',
'platforms',
'first_release_date',
'rating',
'rating_count'
])
->where('rating_count', '>', 0)
->where('category', '=', 0) // Only main games, no DLCs or expansions
->limit($limit)
->orderBy('rating', 'desc');
if ($startTimestamp && $endTimestamp) {
$queryBuilder->where('first_release_date', '>=', $startTimestamp)
->where('first_release_date', '<=', $endTimestamp);
}
if ($query) {
$queryBuilder->search($query);
}
return $queryBuilder->get()->toArray();
} catch (\Exception $e) {
Log::error('Failed to search games', [
'query' => $query,
'error' => $e->getMessage()
]);
return [];
}
}
public function getGameDetails(int $igdbId): ?array
{
try {
$game = IgdbGame::select([
'id',
'name',
'summary',
'storyline',
'cover.url',
'slug',
'first_release_date',
'rating',
'rating_count',
'category',
'status',
'url',
'version_title',
'artworks.url',
'artworks.width',
'artworks.height',
'artworks.image_id',
'screenshots.url',
'screenshots.width',
'screenshots.height',
'screenshots.image_id',
'videos.name',
'videos.video_id',
'videos.url',
'videos.checksum',
'bundles.id',
'collections.id',
'dlcs.id',
'expanded_games.id',
'franchises.id',
'ports.id',
'remakes.id',
'similar_games.id'
])
->where('id', $igdbId)
->first();
if (!$game) {
return null;
}
return $game->toArray();
} catch (\Exception $e) {
Log::error('Failed to fetch game details from IGDB', [
'igdb_id' => $igdbId,
'error' => $e->getMessage()
]);
return null;
}
}
public function getGameCover(int $coverId): ?string
{
try {
return Cover::select(['url'])
->where('id', $coverId)
->first()
?->url;
} catch (\Exception $e) {
Log::error('Failed to get game cover', [
'id' => $coverId,
'error' => $e->getMessage()
]);
return null;
}
}
public function getGenreDetails(int $genreId): ?array
{
try {
return IgdbGenre::select(['id', 'name', 'slug'])
->where('id', $genreId)
->first()
?->toArray();
} catch (\Exception $e) {
Log::error('Failed to get genre details', [
'id' => $genreId,
'error' => $e->getMessage()
]);
return null;
}
}
public function getPlatformDetails(int $platformId): ?array
{
try {
return IgdbPlatform::select(['id', 'name', 'slug', 'abbreviation'])
->where('id', $platformId)
->first()
?->toArray();
} catch (\Exception $e) {
Log::error('Failed to get platform details', [
'id' => $platformId,
'error' => $e->getMessage()
]);
return null;
}
}
public function processGameData(IgdbGame $gameData): Game
{
// Process platforms
$platforms = [];
if (isset($gameData->platforms) && is_array($gameData->platforms)) {
foreach ($gameData->platforms as $platformId) {
if ($platformDetails = $this->getPlatformDetails($platformId)) {
$platform = Platform::updateOrCreate(
['igdb_id' => $platformDetails['id']],
[
'name' => $platformDetails['name'],
'slug' => $platformDetails['slug'],
'abbreviation' => $platformDetails['abbreviation'],
]
);
$platforms[] = $platform->id;
}
}
}
// Create or update the game
$game = Game::updateOrCreate(
['igdb_id' => $gameData->id],
[
'name' => $gameData->name,
'summary' => $gameData->summary ?? null,
'cover_url' => $gameData->cover?->url ?? null,
'slug' => $gameData->slug,
'first_release_date' => $gameData->first_release_date ?? null,
'rating' => $gameData->rating ?? null,
'rating_count' => $gameData->rating_count ?? null,
]
);
// Process artworks
if (isset($gameData->artworks) && is_array($gameData->artworks)) {
foreach ($gameData->artworks as $artwork) {
Artwork::updateOrCreate(
['igdb_id' => $artwork->id],
[
'game_id' => $game->id,
'url' => $artwork->url,
'width' => $artwork->width ?? null,
'height' => $artwork->height ?? null,
'image_id' => $artwork->image_id ?? null,
]
);
}
}
// Process platforms relationship
if (!empty($platforms)) {
$game->platforms()->sync($platforms);
}
// Process screenshots
if (isset($gameData->screenshots) && is_array($gameData->screenshots)) {
foreach ($gameData->screenshots as $screenshot) {
Screenshot::updateOrCreate(
['igdb_id' => $screenshot->id],
[
'game_id' => $game->id,
'url' => $screenshot->url,
'width' => $screenshot->width ?? null,
'height' => $screenshot->height ?? null,
'image_id' => $screenshot->image_id ?? null,
]
);
}
}
// Process videos
if (isset($gameData->videos) && is_array($gameData->videos)) {
foreach ($gameData->videos as $video) {
Video::updateOrCreate(
['igdb_id' => $video->id],
[
'game_id' => $game->id,
'name' => $video->name,
'video_id' => $video->video_id,
'url' => $video->url,
'checksum' => $video->checksum ?? null,
]
);
}
}
// Process relationships
$this->processGameRelationships($game, $gameData);
return $game;
}
private function processGameRelationships(Game $game,IgdbGame $gameData): void
{
// Ensure $gameData is an IgdbGame instance
if (!($gameData instanceof \MarcReichel\IGDBLaravel\Models\Game)) {
throw new \InvalidArgumentException('Game data must be an instance of IgdbGame');
}
$relationships = [
'bundles' => 'bundles',
'collections' => 'collections',
'dlcs' => 'dlcs',
'expanded_games' => 'expansions',
'franchises' => 'franchises',
'ports' => 'ports',
'remakes' => 'remakes',
'similar_games' => 'similarGames',
];
$collections = Collection::where('games', $gameData->identifier)->first();
dd(
$gameData,
$collections
);
foreach ($relationships as $igdbKey => $relationship) {
$relatedGames = [];
if (isset($gameData->$igdbKey) && !empty($gameData->$igdbKey)) {
$relatedIds = collect($gameData->$igdbKey)->pluck('id')->toArray();
$relatedGames = Game::whereIn('igdb_id', $relatedIds)->pluck('id')->toArray();
}
$game->$relationship()->sync($relatedGames);
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.app');
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}