projet par cursor
This commit is contained in:
1 parent
236f75ecdd
commit
b785db1b84
47 files changed
+3902
No files matched your search
+135
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Auth
|
||||
{
|
||||
private const CLE_UTILISATEUR = "utilisateur_id";
|
||||
|
||||
public function __construct(
|
||||
private readonly UtilisateurService $utilisateurService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function demarrerSession(): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_ACTIVE)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
$duree = Config::get("sessionLifetime", 86400);
|
||||
|
||||
session_set_cookie_params([
|
||||
"lifetime" => $duree,
|
||||
"path" => "/",
|
||||
"httponly" => true,
|
||||
"samesite" => "Lax",
|
||||
"secure" => false
|
||||
]);
|
||||
|
||||
session_start();
|
||||
}
|
||||
|
||||
public function connecter(array $utilisateur): void
|
||||
{
|
||||
session_regenerate_id(true);
|
||||
$_SESSION[self::CLE_UTILISATEUR] = $utilisateur["id"];
|
||||
}
|
||||
|
||||
public function deconnecter(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
|
||||
if (ini_get("session.use_cookies"))
|
||||
{
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(
|
||||
session_name(),
|
||||
"",
|
||||
time() - 42000,
|
||||
$params["path"],
|
||||
$params["domain"] ?? "",
|
||||
(bool) $params["secure"],
|
||||
(bool) $params["httponly"]
|
||||
);
|
||||
}
|
||||
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
public function estConnecte(): bool
|
||||
{
|
||||
return $this->utilisateurCourant() !== null;
|
||||
}
|
||||
|
||||
public function utilisateurCourant(): ?array
|
||||
{
|
||||
$id = $_SESSION[self::CLE_UTILISATEUR] ?? null;
|
||||
|
||||
if (!is_string($id) || $id === "")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$utilisateur = $this->utilisateurService->trouverParId($id);
|
||||
|
||||
if ($utilisateur === null || !($utilisateur["actif"] ?? false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return $utilisateur;
|
||||
}
|
||||
|
||||
public function exigerConnexion(): array
|
||||
{
|
||||
$utilisateur = $this->utilisateurCourant();
|
||||
|
||||
if ($utilisateur === null)
|
||||
{
|
||||
Flash::definir("warning", "Veuillez vous connecter pour continuer.");
|
||||
Helpers::rediriger("/connexion");
|
||||
}
|
||||
|
||||
return $utilisateur;
|
||||
}
|
||||
|
||||
public function exigerAdmin(): array
|
||||
{
|
||||
$utilisateur = $this->exigerConnexion();
|
||||
|
||||
if (($utilisateur["role"] ?? "") !== "admin")
|
||||
{
|
||||
Flash::definir("danger", "Accès réservé aux administrateurs.");
|
||||
Helpers::rediriger("/");
|
||||
}
|
||||
|
||||
return $utilisateur;
|
||||
}
|
||||
|
||||
public function tenterConnexion(string $identifiant, string $motDePasse): bool
|
||||
{
|
||||
$utilisateur = $this->utilisateurService->trouverParIdentifiant($identifiant);
|
||||
|
||||
if ($utilisateur === null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!($utilisateur["actif"] ?? false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!password_verify($motDePasse, $utilisateur["motDePasseHash"]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->connecter($utilisateur);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Config
|
||||
{
|
||||
private static array $valeurs = [];
|
||||
|
||||
public static function charger(): void
|
||||
{
|
||||
self::$valeurs = [
|
||||
"appName" => self::env("APP_NAME", "JeuxVideoTech"),
|
||||
"appUrl" => self::env("APP_URL", "http://localhost:8080"),
|
||||
"adminIdentifiant" => self::env("ADMIN_IDENTIFIANT", "admin"),
|
||||
"adminMotDePasse" => self::env("ADMIN_MOT_DE_PASSE", "admin123"),
|
||||
"adminEmail" => self::env("ADMIN_EMAIL", "glainey@planete-online.fr"),
|
||||
"rawgApiKey" => self::env("RAWG_API_KEY", ""),
|
||||
"sessionLifetime" => (int) self::env("SESSION_LIFETIME", "86400"),
|
||||
"dataPath" => dirname(__DIR__) . "/data",
|
||||
"jaquettesPath" => dirname(__DIR__) . "/data/jaquettes",
|
||||
"cachePath" => dirname(__DIR__) . "/data/cache"
|
||||
];
|
||||
}
|
||||
|
||||
public static function get(string $cle, mixed $defaut = null): mixed
|
||||
{
|
||||
return self::$valeurs[$cle] ?? $defaut;
|
||||
}
|
||||
|
||||
private static function env(string $cle, string $defaut = ""): string
|
||||
{
|
||||
$valeur = getenv($cle);
|
||||
|
||||
if ($valeur === false || $valeur === "")
|
||||
{
|
||||
return $defaut;
|
||||
}
|
||||
|
||||
return $valeur;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class AccueilController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Auth $auth,
|
||||
private readonly ConsoleService $consoleService,
|
||||
private readonly JeuService $jeuService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function index(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$utilisateurId = $utilisateur["id"];
|
||||
|
||||
View::rendre("accueil", [
|
||||
"titrePage" => "Accueil",
|
||||
"utilisateur" => $utilisateur,
|
||||
"nombreConsoles" => $this->consoleService->compterPourUtilisateur($utilisateurId),
|
||||
"nombreJeux" => $this->jeuService->compterPourUtilisateur($utilisateurId),
|
||||
"derniersJeux" => $this->jeuService->derniersAjouts($utilisateurId),
|
||||
"consoles" => $this->consoleService->listerPourUtilisateur($utilisateurId)
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class AdminController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Auth $auth,
|
||||
private readonly UtilisateurService $utilisateurService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function index(): void
|
||||
{
|
||||
$admin = $this->auth->exigerAdmin();
|
||||
|
||||
View::rendre("admin/utilisateurs", [
|
||||
"titrePage" => "Administration",
|
||||
"utilisateur" => $admin,
|
||||
"utilisateurs" => $this->utilisateurService->tout()
|
||||
]);
|
||||
}
|
||||
|
||||
public function basculerActif(string $id): void
|
||||
{
|
||||
$admin = $this->auth->exigerAdmin();
|
||||
Csrf::exiger();
|
||||
|
||||
if ($id === $admin["id"])
|
||||
{
|
||||
Flash::definir("warning", "Vous ne pouvez pas désactiver votre propre compte.");
|
||||
Helpers::rediriger("/admin/utilisateurs");
|
||||
}
|
||||
|
||||
$cible = $this->utilisateurService->trouverParId($id);
|
||||
|
||||
if ($cible === null)
|
||||
{
|
||||
Flash::definir("danger", "Utilisateur introuvable.");
|
||||
Helpers::rediriger("/admin/utilisateurs");
|
||||
}
|
||||
|
||||
$nouvelEtat = !($cible["actif"] ?? false);
|
||||
$this->utilisateurService->definirActif($id, $nouvelEtat);
|
||||
|
||||
Flash::definir(
|
||||
"success",
|
||||
$nouvelEtat ? "Compte activé." : "Compte désactivé."
|
||||
);
|
||||
Helpers::rediriger("/admin/utilisateurs");
|
||||
}
|
||||
|
||||
public function supprimer(string $id): void
|
||||
{
|
||||
$admin = $this->auth->exigerAdmin();
|
||||
Csrf::exiger();
|
||||
|
||||
if ($id === $admin["id"])
|
||||
{
|
||||
Flash::definir("warning", "Vous ne pouvez pas supprimer votre propre compte.");
|
||||
Helpers::rediriger("/admin/utilisateurs");
|
||||
}
|
||||
|
||||
if ($this->utilisateurService->supprimer($id))
|
||||
{
|
||||
Flash::definir("success", "Compte supprimé.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Flash::definir("danger", "Utilisateur introuvable.");
|
||||
}
|
||||
|
||||
Helpers::rediriger("/admin/utilisateurs");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class AuthController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Auth $auth,
|
||||
private readonly UtilisateurService $utilisateurService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function connexion(): void
|
||||
{
|
||||
if ($this->auth->estConnecte())
|
||||
{
|
||||
Helpers::rediriger("/");
|
||||
}
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
$identifiant = Helpers::champ("identifiant");
|
||||
$motDePasse = Helpers::champ("motDePasse");
|
||||
|
||||
if ($this->auth->tenterConnexion($identifiant, $motDePasse))
|
||||
{
|
||||
Flash::definir("success", "Bienvenue !");
|
||||
Helpers::rediriger("/");
|
||||
}
|
||||
|
||||
Flash::definir("danger", "Identifiant ou mot de passe incorrect.");
|
||||
}
|
||||
|
||||
View::rendre("auth/connexion", [
|
||||
"titrePage" => "Connexion",
|
||||
"utilisateur" => null
|
||||
], "layout_auth");
|
||||
}
|
||||
|
||||
public function inscription(): void
|
||||
{
|
||||
if ($this->auth->estConnecte())
|
||||
{
|
||||
Helpers::rediriger("/");
|
||||
}
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
try
|
||||
{
|
||||
$utilisateur = $this->utilisateurService->creer(
|
||||
Helpers::champ("identifiant"),
|
||||
Helpers::champ("email"),
|
||||
Helpers::champ("motDePasse"),
|
||||
"utilisateur"
|
||||
);
|
||||
|
||||
$this->auth->connecter($utilisateur);
|
||||
Flash::definir("success", "Compte créé avec succès. Bienvenue !");
|
||||
Helpers::rediriger("/");
|
||||
}
|
||||
catch (InvalidArgumentException $exception)
|
||||
{
|
||||
Flash::definir("danger", $exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
View::rendre("auth/inscription", [
|
||||
"titrePage" => "Inscription",
|
||||
"utilisateur" => null
|
||||
], "layout_auth");
|
||||
}
|
||||
|
||||
public function deconnexion(): void
|
||||
{
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
}
|
||||
|
||||
$this->auth->deconnecter();
|
||||
$this->auth->demarrerSession();
|
||||
Flash::definir("success", "Vous êtes déconnecté.");
|
||||
Helpers::rediriger("/connexion");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class ConsoleController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Auth $auth,
|
||||
private readonly ConsoleService $consoleService,
|
||||
private readonly JeuService $jeuService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function liste(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$consoles = $this->consoleService->listerPourUtilisateur($utilisateur["id"]);
|
||||
|
||||
$jeuxParConsole = [];
|
||||
foreach ($consoles as $console)
|
||||
{
|
||||
$jeuxParConsole[$console["id"]] = count(
|
||||
$this->jeuService->listerParConsole($console["id"], $utilisateur["id"])
|
||||
);
|
||||
}
|
||||
|
||||
View::rendre("consoles/liste", [
|
||||
"titrePage" => "Mes consoles",
|
||||
"utilisateur" => $utilisateur,
|
||||
"consoles" => $consoles,
|
||||
"jeuxParConsole" => $jeuxParConsole
|
||||
]);
|
||||
}
|
||||
|
||||
public function detail(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$console = $this->consoleService->trouverPourUtilisateur($id, $utilisateur["id"]);
|
||||
|
||||
if ($console === null)
|
||||
{
|
||||
Flash::definir("danger", "Console introuvable.");
|
||||
Helpers::rediriger("/consoles");
|
||||
}
|
||||
|
||||
View::rendre("consoles/detail", [
|
||||
"titrePage" => $console["nom"],
|
||||
"utilisateur" => $utilisateur,
|
||||
"console" => $console,
|
||||
"jeux" => $this->jeuService->listerParConsole($id, $utilisateur["id"])
|
||||
]);
|
||||
}
|
||||
|
||||
public function creer(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
try
|
||||
{
|
||||
$console = $this->consoleService->creer($utilisateur["id"], $_POST);
|
||||
Flash::definir("success", "Console ajoutée.");
|
||||
Helpers::rediriger("/consoles/" . $console["id"]);
|
||||
}
|
||||
catch (InvalidArgumentException $exception)
|
||||
{
|
||||
Flash::definir("danger", $exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
View::rendre("consoles/formulaire", [
|
||||
"titrePage" => "Ajouter une console",
|
||||
"utilisateur" => $utilisateur,
|
||||
"console" => null,
|
||||
"action" => "/consoles/creer"
|
||||
]);
|
||||
}
|
||||
|
||||
public function modifier(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$console = $this->consoleService->trouverPourUtilisateur($id, $utilisateur["id"]);
|
||||
|
||||
if ($console === null)
|
||||
{
|
||||
Flash::definir("danger", "Console introuvable.");
|
||||
Helpers::rediriger("/consoles");
|
||||
}
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
try
|
||||
{
|
||||
$console = $this->consoleService->modifier($id, $utilisateur["id"], $_POST);
|
||||
Flash::definir("success", "Console mise à jour.");
|
||||
Helpers::rediriger("/consoles/" . $console["id"]);
|
||||
}
|
||||
catch (InvalidArgumentException $exception)
|
||||
{
|
||||
Flash::definir("danger", $exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
View::rendre("consoles/formulaire", [
|
||||
"titrePage" => "Modifier " . $console["nom"],
|
||||
"utilisateur" => $utilisateur,
|
||||
"console" => $console,
|
||||
"action" => "/consoles/" . $id . "/modifier"
|
||||
]);
|
||||
}
|
||||
|
||||
public function supprimer(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
Csrf::exiger();
|
||||
|
||||
$console = $this->consoleService->trouverPourUtilisateur($id, $utilisateur["id"]);
|
||||
|
||||
if ($console === null)
|
||||
{
|
||||
Flash::definir("danger", "Console introuvable.");
|
||||
Helpers::rediriger("/consoles");
|
||||
}
|
||||
|
||||
$this->jeuService->supprimerParConsole($id, $utilisateur["id"]);
|
||||
$this->consoleService->supprimer($id, $utilisateur["id"]);
|
||||
|
||||
Flash::definir("success", "Console et jeux associés supprimés.");
|
||||
Helpers::rediriger("/consoles");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class JeuController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Auth $auth,
|
||||
private readonly JeuService $jeuService,
|
||||
private readonly ConsoleService $consoleService,
|
||||
private readonly EnrichissementService $enrichissementService
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public function liste(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$recherche = Helpers::champ("q");
|
||||
$consoleId = Helpers::champ("console");
|
||||
$etat = Helpers::champ("etat");
|
||||
|
||||
$jeux = $this->jeuService->listerPourUtilisateur(
|
||||
$utilisateur["id"],
|
||||
$recherche !== "" ? $recherche : null,
|
||||
$consoleId !== "" ? $consoleId : null,
|
||||
$etat !== "" ? $etat : null
|
||||
);
|
||||
|
||||
$consoles = $this->consoleService->listerPourUtilisateur($utilisateur["id"]);
|
||||
$consolesParId = [];
|
||||
|
||||
foreach ($consoles as $console)
|
||||
{
|
||||
$consolesParId[$console["id"]] = $console;
|
||||
}
|
||||
|
||||
View::rendre("jeux/liste", [
|
||||
"titrePage" => "Mes jeux",
|
||||
"utilisateur" => $utilisateur,
|
||||
"jeux" => $jeux,
|
||||
"consoles" => $consoles,
|
||||
"consolesParId" => $consolesParId,
|
||||
"filtres" => [
|
||||
"q" => $recherche,
|
||||
"console" => $consoleId,
|
||||
"etat" => $etat
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
public function detail(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$jeu = $this->jeuService->trouverPourUtilisateur($id, $utilisateur["id"]);
|
||||
|
||||
if ($jeu === null)
|
||||
{
|
||||
Flash::definir("danger", "Jeu introuvable.");
|
||||
Helpers::rediriger("/jeux");
|
||||
}
|
||||
|
||||
$console = $this->consoleService->trouverPourUtilisateur(
|
||||
$jeu["consoleId"],
|
||||
$utilisateur["id"]
|
||||
);
|
||||
|
||||
View::rendre("jeux/detail", [
|
||||
"titrePage" => $jeu["titre"],
|
||||
"utilisateur" => $utilisateur,
|
||||
"jeu" => $jeu,
|
||||
"console" => $console
|
||||
]);
|
||||
}
|
||||
|
||||
public function creer(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$consoles = $this->consoleService->listerPourUtilisateur($utilisateur["id"]);
|
||||
|
||||
if ($consoles === [])
|
||||
{
|
||||
Flash::definir("warning", "Ajoutez d'abord une console avant d'enregistrer un jeu.");
|
||||
Helpers::rediriger("/consoles/creer");
|
||||
}
|
||||
|
||||
$prefill = $this->construirePrefillDepuisGet();
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
try
|
||||
{
|
||||
$donnees = $this->collecterDonneesFormulaire();
|
||||
$jeu = $this->jeuService->creer($utilisateur["id"], $donnees);
|
||||
Flash::definir("success", "Jeu ajouté à votre bibliothèque.");
|
||||
Helpers::rediriger("/jeux/" . $jeu["id"]);
|
||||
}
|
||||
catch (InvalidArgumentException $exception)
|
||||
{
|
||||
Flash::definir("danger", $exception->getMessage());
|
||||
$prefill = array_merge($prefill, $_POST);
|
||||
}
|
||||
}
|
||||
|
||||
View::rendre("jeux/formulaire", [
|
||||
"titrePage" => "Ajouter un jeu",
|
||||
"utilisateur" => $utilisateur,
|
||||
"jeu" => $prefill,
|
||||
"consoles" => $consoles,
|
||||
"action" => "/jeux/creer",
|
||||
"apiDisponible" => $this->enrichissementService->estDisponible()
|
||||
]);
|
||||
}
|
||||
|
||||
public function modifier(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
$jeu = $this->jeuService->trouverPourUtilisateur($id, $utilisateur["id"]);
|
||||
|
||||
if ($jeu === null)
|
||||
{
|
||||
Flash::definir("danger", "Jeu introuvable.");
|
||||
Helpers::rediriger("/jeux");
|
||||
}
|
||||
|
||||
$consoles = $this->consoleService->listerPourUtilisateur($utilisateur["id"]);
|
||||
|
||||
if (Helpers::estPost())
|
||||
{
|
||||
Csrf::exiger();
|
||||
|
||||
try
|
||||
{
|
||||
$donnees = $this->collecterDonneesFormulaire();
|
||||
$jeu = $this->jeuService->modifier($id, $utilisateur["id"], $donnees);
|
||||
Flash::definir("success", "Jeu mis à jour.");
|
||||
Helpers::rediriger("/jeux/" . $jeu["id"]);
|
||||
}
|
||||
catch (InvalidArgumentException $exception)
|
||||
{
|
||||
Flash::definir("danger", $exception->getMessage());
|
||||
$jeu = array_merge($jeu, $_POST);
|
||||
}
|
||||
}
|
||||
|
||||
View::rendre("jeux/formulaire", [
|
||||
"titrePage" => "Modifier " . $jeu["titre"],
|
||||
"utilisateur" => $utilisateur,
|
||||
"jeu" => $jeu,
|
||||
"consoles" => $consoles,
|
||||
"action" => "/jeux/" . $id . "/modifier",
|
||||
"apiDisponible" => $this->enrichissementService->estDisponible()
|
||||
]);
|
||||
}
|
||||
|
||||
public function supprimer(string $id): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
Csrf::exiger();
|
||||
|
||||
if ($this->jeuService->supprimer($id, $utilisateur["id"]))
|
||||
{
|
||||
Flash::definir("success", "Jeu supprimé.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Flash::definir("danger", "Jeu introuvable.");
|
||||
}
|
||||
|
||||
Helpers::rediriger("/jeux");
|
||||
}
|
||||
|
||||
public function rechercherApi(): void
|
||||
{
|
||||
$this->auth->exigerConnexion();
|
||||
|
||||
header("Content-Type: application/json; charset=utf-8");
|
||||
|
||||
$titre = Helpers::champ("q");
|
||||
|
||||
if ($titre === "")
|
||||
{
|
||||
print json_encode(["resultats" => []]);
|
||||
return;
|
||||
}
|
||||
|
||||
$resultats = $this->enrichissementService->rechercher($titre);
|
||||
print json_encode(["resultats" => $resultats], JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
public function appliquerEnrichissement(): void
|
||||
{
|
||||
$utilisateur = $this->auth->exigerConnexion();
|
||||
Csrf::exiger();
|
||||
|
||||
$rawgId = (int) Helpers::champ("rawgId");
|
||||
$retour = Helpers::champ("retour", "/jeux/creer");
|
||||
|
||||
if ($rawgId <= 0)
|
||||
{
|
||||
Flash::definir("danger", "Sélection d'enrichissement invalide.");
|
||||
Helpers::rediriger($retour);
|
||||
}
|
||||
|
||||
$detail = $this->enrichissementService->detail($rawgId);
|
||||
|
||||
if ($detail === null)
|
||||
{
|
||||
Flash::definir("warning", "Impossible de récupérer les métadonnées. Saisie manuelle possible.");
|
||||
Helpers::rediriger($retour);
|
||||
}
|
||||
|
||||
$jaquette = $this->enrichissementService->telechargerJaquette($detail["jaquetteUrl"] ?? null);
|
||||
|
||||
$query = http_build_query([
|
||||
"titre" => $detail["titre"] ?? "",
|
||||
"description" => $detail["description"] ?? "",
|
||||
"dateSortie" => $detail["dateSortie"] ?? "",
|
||||
"genres" => implode(", ", $detail["genres"] ?? []),
|
||||
"editeur" => $detail["editeur"] ?? "",
|
||||
"developpeur" => $detail["developpeur"] ?? "",
|
||||
"jaquette" => $jaquette ?? "",
|
||||
"sourceEnrichissement" => "api"
|
||||
]);
|
||||
|
||||
$separateur = str_contains($retour, "?") ? "&" : "?";
|
||||
Helpers::rediriger($retour . $separateur . $query);
|
||||
}
|
||||
|
||||
private function collecterDonneesFormulaire(): array
|
||||
{
|
||||
return [
|
||||
"titre" => Helpers::champ("titre"),
|
||||
"consoleId" => Helpers::champ("consoleId"),
|
||||
"etat" => Helpers::champ("etat", "possede"),
|
||||
"jaquette" => Helpers::champ("jaquette"),
|
||||
"description" => Helpers::champ("description"),
|
||||
"dateSortie" => Helpers::champ("dateSortie"),
|
||||
"genres" => Helpers::champ("genres"),
|
||||
"editeur" => Helpers::champ("editeur"),
|
||||
"developpeur" => Helpers::champ("developpeur"),
|
||||
"notes" => Helpers::champ("notes"),
|
||||
"sourceEnrichissement" => Helpers::champ("sourceEnrichissement", "manuel")
|
||||
];
|
||||
}
|
||||
|
||||
private function construirePrefillDepuisGet(): array
|
||||
{
|
||||
$genres = Helpers::champ("genres");
|
||||
|
||||
return [
|
||||
"titre" => Helpers::champ("titre"),
|
||||
"consoleId" => Helpers::champ("consoleId"),
|
||||
"etat" => Helpers::champ("etat", "possede"),
|
||||
"jaquette" => Helpers::champ("jaquette"),
|
||||
"description" => Helpers::champ("description"),
|
||||
"dateSortie" => Helpers::champ("dateSortie"),
|
||||
"genres" => $genres !== "" ? array_map("trim", explode(",", $genres)) : [],
|
||||
"editeur" => Helpers::champ("editeur"),
|
||||
"developpeur" => Helpers::champ("developpeur"),
|
||||
"notes" => Helpers::champ("notes"),
|
||||
"sourceEnrichissement" => Helpers::champ("sourceEnrichissement", "manuel")
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Csrf
|
||||
{
|
||||
private const CLE_SESSION = "_csrf_token";
|
||||
|
||||
public static function genererToken(): string
|
||||
{
|
||||
if (empty($_SESSION[self::CLE_SESSION]))
|
||||
{
|
||||
$_SESSION[self::CLE_SESSION] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
return $_SESSION[self::CLE_SESSION];
|
||||
}
|
||||
|
||||
public static function champCache(): string
|
||||
{
|
||||
$token = htmlspecialchars(self::genererToken(), ENT_QUOTES, "UTF-8");
|
||||
|
||||
return '<input type="hidden" name="_csrf" value="' . $token . '">';
|
||||
}
|
||||
|
||||
public static function verifier(?string $token): bool
|
||||
{
|
||||
if ($token === null || empty($_SESSION[self::CLE_SESSION]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return hash_equals($_SESSION[self::CLE_SESSION], $token);
|
||||
}
|
||||
|
||||
public static function exiger(): void
|
||||
{
|
||||
$token = $_POST["_csrf"] ?? null;
|
||||
|
||||
if (!self::verifier(is_string($token) ? $token : null))
|
||||
{
|
||||
http_response_code(403);
|
||||
exit("Requête refusée : jeton CSRF invalide.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Flash
|
||||
{
|
||||
private const CLE = "_flash";
|
||||
|
||||
public static function definir(string $type, string $message): void
|
||||
{
|
||||
$_SESSION[self::CLE] = [
|
||||
"type" => $type,
|
||||
"message" => $message
|
||||
];
|
||||
}
|
||||
|
||||
public static function consommer(): ?array
|
||||
{
|
||||
if (empty($_SESSION[self::CLE]))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$flash = $_SESSION[self::CLE];
|
||||
unset($_SESSION[self::CLE]);
|
||||
|
||||
return $flash;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Helpers
|
||||
{
|
||||
public static function genererId(): string
|
||||
{
|
||||
return bin2hex(random_bytes(16));
|
||||
}
|
||||
|
||||
public static function maintenant(): string
|
||||
{
|
||||
return gmdate("c");
|
||||
}
|
||||
|
||||
public static function echapper(?string $valeur): string
|
||||
{
|
||||
return htmlspecialchars((string) $valeur, ENT_QUOTES, "UTF-8");
|
||||
}
|
||||
|
||||
public static function rediriger(string $chemin): never
|
||||
{
|
||||
header("Location: " . $chemin);
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function estPost(): bool
|
||||
{
|
||||
return strtoupper($_SERVER["REQUEST_METHOD"] ?? "GET") === "POST";
|
||||
}
|
||||
|
||||
public static function champ(string $nom, string $defaut = ""): string
|
||||
{
|
||||
$valeur = $_POST[$nom] ?? $_GET[$nom] ?? $defaut;
|
||||
|
||||
return is_string($valeur) ? trim($valeur) : $defaut;
|
||||
}
|
||||
|
||||
public static function etatsJeu(): array
|
||||
{
|
||||
return [
|
||||
"possede" => "Possédé",
|
||||
"a_acheter" => "À acheter",
|
||||
"prete" => "Prêté",
|
||||
"vendu" => "Vendu"
|
||||
];
|
||||
}
|
||||
|
||||
public static function libelleEtat(string $etat): string
|
||||
{
|
||||
return self::etatsJeu()[$etat] ?? $etat;
|
||||
}
|
||||
|
||||
public static function urlJaquette(?string $chemin): string
|
||||
{
|
||||
if ($chemin === null || $chemin === "")
|
||||
{
|
||||
return "/assets/img/jaquette-manquante.svg";
|
||||
}
|
||||
|
||||
if (str_starts_with($chemin, "http://") || str_starts_with($chemin, "https://"))
|
||||
{
|
||||
return $chemin;
|
||||
}
|
||||
|
||||
return "/jaquettes/" . ltrim($chemin, "/");
|
||||
}
|
||||
|
||||
public static function tronquer(string $texte, int $longueur = 140): string
|
||||
{
|
||||
if (mb_strlen($texte) <= $longueur)
|
||||
{
|
||||
return $texte;
|
||||
}
|
||||
|
||||
return mb_substr($texte, 0, $longueur - 1) . "…";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Stockage simple basé sur un fichier JSON.
|
||||
* Chaque opération lit / écrit le fichier complet avec un verrou exclusif.
|
||||
*/
|
||||
final class JsonStore
|
||||
{
|
||||
private string $cheminFichier;
|
||||
|
||||
public function __construct(string $cheminFichier)
|
||||
{
|
||||
$this->cheminFichier = $cheminFichier;
|
||||
$this->assurerFichier();
|
||||
}
|
||||
|
||||
public function tout(): array
|
||||
{
|
||||
$contenu = file_get_contents($this->cheminFichier);
|
||||
|
||||
if ($contenu === false || trim($contenu) === "")
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
$donnees = json_decode($contenu, true);
|
||||
|
||||
return is_array($donnees) ? $donnees : [];
|
||||
}
|
||||
|
||||
public function trouverParId(string $id): ?array
|
||||
{
|
||||
foreach ($this->tout() as $element)
|
||||
{
|
||||
if (($element["id"] ?? null) === $id)
|
||||
{
|
||||
return $element;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function filtrer(callable $filtre): array
|
||||
{
|
||||
return array_values(array_filter($this->tout(), $filtre));
|
||||
}
|
||||
|
||||
public function ajouter(array $element): array
|
||||
{
|
||||
return $this->avecVerrou(function (array &$donnees) use ($element): array
|
||||
{
|
||||
$donnees[] = $element;
|
||||
|
||||
return $element;
|
||||
});
|
||||
}
|
||||
|
||||
public function mettreAJour(string $id, array $nouveauxChamps): ?array
|
||||
{
|
||||
return $this->avecVerrou(function (array &$donnees) use ($id, $nouveauxChamps): ?array
|
||||
{
|
||||
foreach ($donnees as $index => $element)
|
||||
{
|
||||
if (($element["id"] ?? null) !== $id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$donnees[$index] = array_merge($element, $nouveauxChamps);
|
||||
|
||||
return $donnees[$index];
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public function supprimer(string $id): bool
|
||||
{
|
||||
return $this->avecVerrou(function (array &$donnees) use ($id): bool
|
||||
{
|
||||
$tailleInitiale = count($donnees);
|
||||
$donnees = array_values(array_filter(
|
||||
$donnees,
|
||||
static fn (array $element): bool => ($element["id"] ?? null) !== $id
|
||||
));
|
||||
|
||||
return count($donnees) !== $tailleInitiale;
|
||||
});
|
||||
}
|
||||
|
||||
public function remplacerTout(array $donnees): void
|
||||
{
|
||||
$this->avecVerrou(function (array &$existantes) use ($donnees): null
|
||||
{
|
||||
$existantes = $donnees;
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private function assurerFichier(): void
|
||||
{
|
||||
$dossier = dirname($this->cheminFichier);
|
||||
|
||||
if (!is_dir($dossier))
|
||||
{
|
||||
mkdir($dossier, 0775, true);
|
||||
}
|
||||
|
||||
if (!file_exists($this->cheminFichier))
|
||||
{
|
||||
file_put_contents($this->cheminFichier, "[]" . PHP_EOL, LOCK_EX);
|
||||
}
|
||||
}
|
||||
|
||||
private function avecVerrou(callable $callback): mixed
|
||||
{
|
||||
$handle = fopen($this->cheminFichier, "c+");
|
||||
|
||||
if ($handle === false)
|
||||
{
|
||||
throw new RuntimeException("Impossible d'ouvrir " . $this->cheminFichier);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
flock($handle, LOCK_EX);
|
||||
rewind($handle);
|
||||
$contenu = stream_get_contents($handle);
|
||||
$donnees = [];
|
||||
|
||||
if ($contenu !== false && trim($contenu) !== "")
|
||||
{
|
||||
$decode = json_decode($contenu, true);
|
||||
$donnees = is_array($decode) ? $decode : [];
|
||||
}
|
||||
|
||||
$resultat = $callback($donnees);
|
||||
|
||||
$json = json_encode(
|
||||
$donnees,
|
||||
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
|
||||
);
|
||||
|
||||
ftruncate($handle, 0);
|
||||
rewind($handle);
|
||||
fwrite($handle, $json . PHP_EOL);
|
||||
fflush($handle);
|
||||
|
||||
return $resultat;
|
||||
}
|
||||
finally
|
||||
{
|
||||
flock($handle, LOCK_UN);
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Router
|
||||
{
|
||||
private array $routes = [];
|
||||
|
||||
public function get(string $chemin, callable $action): void
|
||||
{
|
||||
$this->ajouter("GET", $chemin, $action);
|
||||
}
|
||||
|
||||
public function post(string $chemin, callable $action): void
|
||||
{
|
||||
$this->ajouter("POST", $chemin, $action);
|
||||
}
|
||||
|
||||
public function dispatcher(string $methode, string $uri): void
|
||||
{
|
||||
$chemin = parse_url($uri, PHP_URL_PATH) ?: "/";
|
||||
$chemin = rtrim($chemin, "/") ?: "/";
|
||||
|
||||
foreach ($this->routes as $route)
|
||||
{
|
||||
if ($route["methode"] !== strtoupper($methode))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$motif = "@^" . $route["motif"] . "$@";
|
||||
|
||||
if (!preg_match($motif, $chemin, $captures))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = array_filter(
|
||||
$captures,
|
||||
static fn ($cle): bool => !is_int($cle),
|
||||
ARRAY_FILTER_USE_KEY
|
||||
);
|
||||
|
||||
call_user_func_array($route["action"], array_values($params));
|
||||
return;
|
||||
}
|
||||
|
||||
http_response_code(404);
|
||||
View::rendre("erreurs/404", [
|
||||
"titrePage" => "Page introuvable",
|
||||
"utilisateur" => null
|
||||
], "layout_auth");
|
||||
}
|
||||
|
||||
private function ajouter(string $methode, string $chemin, callable $action): void
|
||||
{
|
||||
$motif = preg_replace("#\{([a-zA-Z_]+)\}#", "(?P<$1>[^/]+)", $chemin);
|
||||
$motif = str_replace("/", "\/", $motif ?? $chemin);
|
||||
|
||||
$this->routes[] = [
|
||||
"methode" => $methode,
|
||||
"motif" => $motif,
|
||||
"action" => $action
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class ConsoleService
|
||||
{
|
||||
private JsonStore $store;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->store = new JsonStore(Config::get("dataPath") . "/consoles.json");
|
||||
}
|
||||
|
||||
public function listerPourUtilisateur(string $utilisateurId): array
|
||||
{
|
||||
$consoles = $this->store->filtrer(
|
||||
static fn (array $console): bool => ($console["utilisateurId"] ?? "") === $utilisateurId
|
||||
);
|
||||
|
||||
usort(
|
||||
$consoles,
|
||||
static fn (array $a, array $b): int => strcmp($a["nom"] ?? "", $b["nom"] ?? "")
|
||||
);
|
||||
|
||||
return $consoles;
|
||||
}
|
||||
|
||||
public function trouverPourUtilisateur(string $id, string $utilisateurId): ?array
|
||||
{
|
||||
$console = $this->store->trouverParId($id);
|
||||
|
||||
if ($console === null || ($console["utilisateurId"] ?? "") !== $utilisateurId)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return $console;
|
||||
}
|
||||
|
||||
public function creer(string $utilisateurId, array $donnees): array
|
||||
{
|
||||
$nom = trim((string) ($donnees["nom"] ?? ""));
|
||||
$constructeur = trim((string) ($donnees["constructeur"] ?? ""));
|
||||
|
||||
if ($nom === "" || $constructeur === "")
|
||||
{
|
||||
throw new InvalidArgumentException("Le nom et le constructeur sont obligatoires.");
|
||||
}
|
||||
|
||||
$annee = $this->normaliserAnnee($donnees["annee"] ?? null);
|
||||
$maintenant = Helpers::maintenant();
|
||||
|
||||
$console = [
|
||||
"id" => Helpers::genererId(),
|
||||
"utilisateurId" => $utilisateurId,
|
||||
"nom" => $nom,
|
||||
"constructeur" => $constructeur,
|
||||
"annee" => $annee,
|
||||
"notes" => trim((string) ($donnees["notes"] ?? "")),
|
||||
"createdAt" => $maintenant,
|
||||
"updatedAt" => $maintenant
|
||||
];
|
||||
|
||||
return $this->store->ajouter($console);
|
||||
}
|
||||
|
||||
public function modifier(string $id, string $utilisateurId, array $donnees): array
|
||||
{
|
||||
$console = $this->trouverPourUtilisateur($id, $utilisateurId);
|
||||
|
||||
if ($console === null)
|
||||
{
|
||||
throw new RuntimeException("Console introuvable.");
|
||||
}
|
||||
|
||||
$nom = trim((string) ($donnees["nom"] ?? ""));
|
||||
$constructeur = trim((string) ($donnees["constructeur"] ?? ""));
|
||||
|
||||
if ($nom === "" || $constructeur === "")
|
||||
{
|
||||
throw new InvalidArgumentException("Le nom et le constructeur sont obligatoires.");
|
||||
}
|
||||
|
||||
$miseAJour = $this->store->mettreAJour($id, [
|
||||
"nom" => $nom,
|
||||
"constructeur" => $constructeur,
|
||||
"annee" => $this->normaliserAnnee($donnees["annee"] ?? null),
|
||||
"notes" => trim((string) ($donnees["notes"] ?? "")),
|
||||
"updatedAt" => Helpers::maintenant()
|
||||
]);
|
||||
|
||||
if ($miseAJour === null)
|
||||
{
|
||||
throw new RuntimeException("Échec de la mise à jour.");
|
||||
}
|
||||
|
||||
return $miseAJour;
|
||||
}
|
||||
|
||||
public function supprimer(string $id, string $utilisateurId): bool
|
||||
{
|
||||
$console = $this->trouverPourUtilisateur($id, $utilisateurId);
|
||||
|
||||
if ($console === null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->store->supprimer($id);
|
||||
}
|
||||
|
||||
public function compterPourUtilisateur(string $utilisateurId): int
|
||||
{
|
||||
return count($this->listerPourUtilisateur($utilisateurId));
|
||||
}
|
||||
|
||||
private function normaliserAnnee(mixed $annee): ?int
|
||||
{
|
||||
if ($annee === null || $annee === "")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$valeur = (int) $annee;
|
||||
|
||||
if ($valeur < 1970 || $valeur > (int) date("Y") + 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return $valeur;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Enrichissement via l'API RAWG (https://rawg.io/apidocs).
|
||||
* Si la clé API est absente ou l'API indisponible, renvoie une liste vide.
|
||||
*/
|
||||
final class EnrichissementService
|
||||
{
|
||||
private const BASE_URL = "https://api.rawg.io/api";
|
||||
|
||||
public function estDisponible(): bool
|
||||
{
|
||||
return Config::get("rawgApiKey", "") !== "";
|
||||
}
|
||||
|
||||
public function rechercher(string $titre, int $limite = 8): array
|
||||
{
|
||||
$titre = trim($titre);
|
||||
|
||||
if ($titre === "" || !$this->estDisponible())
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
$cacheCle = "recherche_" . md5(mb_strtolower($titre));
|
||||
$cache = $this->lireCache($cacheCle);
|
||||
|
||||
if ($cache !== null)
|
||||
{
|
||||
return array_slice($cache, 0, $limite);
|
||||
}
|
||||
|
||||
$reponse = $this->appeler("/games", [
|
||||
"search" => $titre,
|
||||
"page_size" => $limite
|
||||
]);
|
||||
|
||||
if ($reponse === null || !isset($reponse["results"]) || !is_array($reponse["results"]))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
$resultats = [];
|
||||
|
||||
foreach ($reponse["results"] as $jeu)
|
||||
{
|
||||
$resultats[] = $this->mapperResultatListe($jeu);
|
||||
}
|
||||
|
||||
$this->ecrireCache($cacheCle, $resultats);
|
||||
|
||||
return $resultats;
|
||||
}
|
||||
|
||||
public function detail(int $rawgId): ?array
|
||||
{
|
||||
if (!$this->estDisponible())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$cacheCle = "detail_" . $rawgId;
|
||||
$cache = $this->lireCache($cacheCle);
|
||||
|
||||
if ($cache !== null)
|
||||
{
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$reponse = $this->appeler("/games/" . $rawgId);
|
||||
|
||||
if ($reponse === null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$detail = $this->mapperDetail($reponse);
|
||||
$this->ecrireCache($cacheCle, $detail);
|
||||
|
||||
return $detail;
|
||||
}
|
||||
|
||||
public function telechargerJaquette(?string $urlImage): ?string
|
||||
{
|
||||
if ($urlImage === null || $urlImage === "")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$extension = pathinfo(parse_url($urlImage, PHP_URL_PATH) ?? "", PATHINFO_EXTENSION);
|
||||
$extension = $extension !== "" ? strtolower($extension) : "jpg";
|
||||
|
||||
if (!in_array($extension, ["jpg", "jpeg", "png", "webp", "gif"], true))
|
||||
{
|
||||
$extension = "jpg";
|
||||
}
|
||||
|
||||
$nomFichier = Helpers::genererId() . "." . $extension;
|
||||
$cheminLocal = Config::get("jaquettesPath") . "/" . $nomFichier;
|
||||
|
||||
$contexte = stream_context_create([
|
||||
"http" => [
|
||||
"timeout" => 10,
|
||||
"header" => "User-Agent: JeuxVideoTech/1.0\r\n"
|
||||
]
|
||||
]);
|
||||
|
||||
$contenu = @file_get_contents($urlImage, false, $contexte);
|
||||
|
||||
if ($contenu === false)
|
||||
{
|
||||
return $urlImage;
|
||||
}
|
||||
|
||||
if (file_put_contents($cheminLocal, $contenu) === false)
|
||||
{
|
||||
return $urlImage;
|
||||
}
|
||||
|
||||
return $nomFichier;
|
||||
}
|
||||
|
||||
private function mapperResultatListe(array $jeu): array
|
||||
{
|
||||
$genres = [];
|
||||
|
||||
foreach ($jeu["genres"] ?? [] as $genre)
|
||||
{
|
||||
if (!empty($genre["name"]))
|
||||
{
|
||||
$genres[] = $genre["name"];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
"rawgId" => (int) ($jeu["id"] ?? 0),
|
||||
"titre" => (string) ($jeu["name"] ?? ""),
|
||||
"dateSortie" => $jeu["released"] ?? null,
|
||||
"jaquetteUrl" => $jeu["background_image"] ?? null,
|
||||
"genres" => $genres,
|
||||
"note" => $jeu["rating"] ?? null
|
||||
];
|
||||
}
|
||||
|
||||
private function mapperDetail(array $jeu): array
|
||||
{
|
||||
$base = $this->mapperResultatListe($jeu);
|
||||
|
||||
$editeurs = [];
|
||||
foreach ($jeu["publishers"] ?? [] as $editeur)
|
||||
{
|
||||
if (!empty($editeur["name"]))
|
||||
{
|
||||
$editeurs[] = $editeur["name"];
|
||||
}
|
||||
}
|
||||
|
||||
$developpeurs = [];
|
||||
foreach ($jeu["developers"] ?? [] as $developpeur)
|
||||
{
|
||||
if (!empty($developpeur["name"]))
|
||||
{
|
||||
$developpeurs[] = $developpeur["name"];
|
||||
}
|
||||
}
|
||||
|
||||
$description = (string) ($jeu["description_raw"] ?? "");
|
||||
|
||||
if ($description === "" && !empty($jeu["description"]))
|
||||
{
|
||||
$description = trim(strip_tags((string) $jeu["description"]));
|
||||
}
|
||||
|
||||
return array_merge($base, [
|
||||
"description" => $description,
|
||||
"editeur" => implode(", ", $editeurs),
|
||||
"developpeur" => implode(", ", $developpeurs)
|
||||
]);
|
||||
}
|
||||
|
||||
private function appeler(string $chemin, array $params = []): ?array
|
||||
{
|
||||
$params["key"] = Config::get("rawgApiKey");
|
||||
$url = self::BASE_URL . $chemin . "?" . http_build_query($params);
|
||||
|
||||
$contexte = stream_context_create([
|
||||
"http" => [
|
||||
"method" => "GET",
|
||||
"timeout" => 8,
|
||||
"header" => "User-Agent: JeuxVideoTech/1.0\r\nAccept: application/json\r\n"
|
||||
]
|
||||
]);
|
||||
|
||||
$reponse = @file_get_contents($url, false, $contexte);
|
||||
|
||||
if ($reponse === false)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$donnees = json_decode($reponse, true);
|
||||
|
||||
return is_array($donnees) ? $donnees : null;
|
||||
}
|
||||
|
||||
private function lireCache(string $cle): ?array
|
||||
{
|
||||
$fichier = Config::get("cachePath") . "/" . $cle . ".json";
|
||||
|
||||
if (!is_file($fichier))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (filemtime($fichier) < time() - 86400)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$contenu = file_get_contents($fichier);
|
||||
|
||||
if ($contenu === false)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$donnees = json_decode($contenu, true);
|
||||
|
||||
return is_array($donnees) ? $donnees : null;
|
||||
}
|
||||
|
||||
private function ecrireCache(string $cle, array $donnees): void
|
||||
{
|
||||
$dossier = Config::get("cachePath");
|
||||
|
||||
if (!is_dir($dossier))
|
||||
{
|
||||
mkdir($dossier, 0775, true);
|
||||
}
|
||||
|
||||
$fichier = $dossier . "/" . $cle . ".json";
|
||||
file_put_contents(
|
||||
$fichier,
|
||||
json_encode($donnees, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
LOCK_EX
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class JeuService
|
||||
{
|
||||
private JsonStore $store;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->store = new JsonStore(Config::get("dataPath") . "/jeux.json");
|
||||
}
|
||||
|
||||
public function listerPourUtilisateur(
|
||||
string $utilisateurId,
|
||||
?string $recherche = null,
|
||||
?string $consoleId = null,
|
||||
?string $etat = null
|
||||
): array
|
||||
{
|
||||
$jeux = $this->store->filtrer(
|
||||
static fn (array $jeu): bool => ($jeu["utilisateurId"] ?? "") === $utilisateurId
|
||||
);
|
||||
|
||||
if ($consoleId !== null && $consoleId !== "")
|
||||
{
|
||||
$jeux = array_values(array_filter(
|
||||
$jeux,
|
||||
static fn (array $jeu): bool => ($jeu["consoleId"] ?? "") === $consoleId
|
||||
));
|
||||
}
|
||||
|
||||
if ($etat !== null && $etat !== "")
|
||||
{
|
||||
$jeux = array_values(array_filter(
|
||||
$jeux,
|
||||
static fn (array $jeu): bool => ($jeu["etat"] ?? "") === $etat
|
||||
));
|
||||
}
|
||||
|
||||
if ($recherche !== null && $recherche !== "")
|
||||
{
|
||||
$terme = mb_strtolower($recherche);
|
||||
$jeux = array_values(array_filter(
|
||||
$jeux,
|
||||
static function (array $jeu) use ($terme): bool
|
||||
{
|
||||
$champs = [
|
||||
$jeu["titre"] ?? "",
|
||||
$jeu["description"] ?? "",
|
||||
$jeu["editeur"] ?? "",
|
||||
$jeu["developpeur"] ?? "",
|
||||
implode(" ", $jeu["genres"] ?? [])
|
||||
];
|
||||
|
||||
return str_contains(mb_strtolower(implode(" ", $champs)), $terme);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
usort(
|
||||
$jeux,
|
||||
static fn (array $a, array $b): int => strcmp($a["titre"] ?? "", $b["titre"] ?? "")
|
||||
);
|
||||
|
||||
return $jeux;
|
||||
}
|
||||
|
||||
public function trouverPourUtilisateur(string $id, string $utilisateurId): ?array
|
||||
{
|
||||
$jeu = $this->store->trouverParId($id);
|
||||
|
||||
if ($jeu === null || ($jeu["utilisateurId"] ?? "") !== $utilisateurId)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return $jeu;
|
||||
}
|
||||
|
||||
public function listerParConsole(string $consoleId, string $utilisateurId): array
|
||||
{
|
||||
return $this->listerPourUtilisateur($utilisateurId, null, $consoleId, null);
|
||||
}
|
||||
|
||||
public function derniersAjouts(string $utilisateurId, int $limite = 6): array
|
||||
{
|
||||
$jeux = $this->listerPourUtilisateur($utilisateurId);
|
||||
|
||||
usort(
|
||||
$jeux,
|
||||
static fn (array $a, array $b): int => strcmp($b["createdAt"] ?? "", $a["createdAt"] ?? "")
|
||||
);
|
||||
|
||||
return array_slice($jeux, 0, $limite);
|
||||
}
|
||||
|
||||
public function creer(string $utilisateurId, array $donnees): array
|
||||
{
|
||||
$jeu = $this->preparerDonnees($utilisateurId, $donnees);
|
||||
$maintenant = Helpers::maintenant();
|
||||
|
||||
$jeu["id"] = Helpers::genererId();
|
||||
$jeu["utilisateurId"] = $utilisateurId;
|
||||
$jeu["createdAt"] = $maintenant;
|
||||
$jeu["updatedAt"] = $maintenant;
|
||||
|
||||
return $this->store->ajouter($jeu);
|
||||
}
|
||||
|
||||
public function modifier(string $id, string $utilisateurId, array $donnees): array
|
||||
{
|
||||
$existant = $this->trouverPourUtilisateur($id, $utilisateurId);
|
||||
|
||||
if ($existant === null)
|
||||
{
|
||||
throw new RuntimeException("Jeu introuvable.");
|
||||
}
|
||||
|
||||
$jeu = $this->preparerDonnees($utilisateurId, $donnees, $existant);
|
||||
$jeu["updatedAt"] = Helpers::maintenant();
|
||||
|
||||
$miseAJour = $this->store->mettreAJour($id, $jeu);
|
||||
|
||||
if ($miseAJour === null)
|
||||
{
|
||||
throw new RuntimeException("Échec de la mise à jour.");
|
||||
}
|
||||
|
||||
return $miseAJour;
|
||||
}
|
||||
|
||||
public function supprimer(string $id, string $utilisateurId): bool
|
||||
{
|
||||
$jeu = $this->trouverPourUtilisateur($id, $utilisateurId);
|
||||
|
||||
if ($jeu === null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->supprimerJaquetteLocale($jeu["jaquette"] ?? null);
|
||||
|
||||
return $this->store->supprimer($id);
|
||||
}
|
||||
|
||||
public function compterPourUtilisateur(string $utilisateurId): int
|
||||
{
|
||||
return count($this->listerPourUtilisateur($utilisateurId));
|
||||
}
|
||||
|
||||
public function supprimerParConsole(string $consoleId, string $utilisateurId): int
|
||||
{
|
||||
$jeux = $this->listerParConsole($consoleId, $utilisateurId);
|
||||
$compteur = 0;
|
||||
|
||||
foreach ($jeux as $jeu)
|
||||
{
|
||||
if ($this->supprimer($jeu["id"], $utilisateurId))
|
||||
{
|
||||
$compteur++;
|
||||
}
|
||||
}
|
||||
|
||||
return $compteur;
|
||||
}
|
||||
|
||||
private function preparerDonnees(string $utilisateurId, array $donnees, ?array $existant = null): array
|
||||
{
|
||||
$titre = trim((string) ($donnees["titre"] ?? ""));
|
||||
$consoleId = trim((string) ($donnees["consoleId"] ?? ""));
|
||||
$etat = trim((string) ($donnees["etat"] ?? "possede"));
|
||||
|
||||
if ($titre === "" || $consoleId === "")
|
||||
{
|
||||
throw new InvalidArgumentException("Le titre et la console sont obligatoires.");
|
||||
}
|
||||
|
||||
if (!array_key_exists($etat, Helpers::etatsJeu()))
|
||||
{
|
||||
throw new InvalidArgumentException("État de jeu invalide.");
|
||||
}
|
||||
|
||||
$genres = $donnees["genres"] ?? [];
|
||||
|
||||
if (is_string($genres))
|
||||
{
|
||||
$genres = array_values(array_filter(array_map("trim", explode(",", $genres))));
|
||||
}
|
||||
|
||||
if (!is_array($genres))
|
||||
{
|
||||
$genres = [];
|
||||
}
|
||||
|
||||
$jaquette = trim((string) ($donnees["jaquette"] ?? ($existant["jaquette"] ?? "")));
|
||||
|
||||
return [
|
||||
"titre" => $titre,
|
||||
"consoleId" => $consoleId,
|
||||
"etat" => $etat,
|
||||
"jaquette" => $jaquette,
|
||||
"description" => trim((string) ($donnees["description"] ?? "")),
|
||||
"dateSortie" => $this->normaliserDate($donnees["dateSortie"] ?? null),
|
||||
"genres" => array_values($genres),
|
||||
"editeur" => trim((string) ($donnees["editeur"] ?? "")),
|
||||
"developpeur" => trim((string) ($donnees["developpeur"] ?? "")),
|
||||
"notes" => trim((string) ($donnees["notes"] ?? "")),
|
||||
"sourceEnrichissement" => trim((string) ($donnees["sourceEnrichissement"] ?? "manuel"))
|
||||
];
|
||||
}
|
||||
|
||||
private function normaliserDate(mixed $date): ?string
|
||||
{
|
||||
if ($date === null || $date === "")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = (string) $date;
|
||||
|
||||
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $date))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
|
||||
private function supprimerJaquetteLocale(?string $chemin): void
|
||||
{
|
||||
if ($chemin === null || $chemin === "")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (str_starts_with($chemin, "http://") || str_starts_with($chemin, "https://"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
$fichier = Config::get("jaquettesPath") . "/" . basename($chemin);
|
||||
|
||||
if (is_file($fichier))
|
||||
{
|
||||
unlink($fichier);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class UtilisateurService
|
||||
{
|
||||
private JsonStore $store;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->store = new JsonStore(Config::get("dataPath") . "/utilisateurs.json");
|
||||
}
|
||||
|
||||
public function tout(): array
|
||||
{
|
||||
$utilisateurs = $this->store->tout();
|
||||
usort(
|
||||
$utilisateurs,
|
||||
static fn (array $a, array $b): int => strcmp($a["identifiant"] ?? "", $b["identifiant"] ?? "")
|
||||
);
|
||||
|
||||
return $utilisateurs;
|
||||
}
|
||||
|
||||
public function trouverParId(string $id): ?array
|
||||
{
|
||||
return $this->store->trouverParId($id);
|
||||
}
|
||||
|
||||
public function trouverParIdentifiant(string $identifiant): ?array
|
||||
{
|
||||
$identifiant = mb_strtolower(trim($identifiant));
|
||||
|
||||
foreach ($this->store->tout() as $utilisateur)
|
||||
{
|
||||
if (mb_strtolower($utilisateur["identifiant"] ?? "") === $identifiant)
|
||||
{
|
||||
return $utilisateur;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function creer(string $identifiant, string $email, string $motDePasse, string $role = "utilisateur"): array
|
||||
{
|
||||
$identifiant = trim($identifiant);
|
||||
$email = trim($email);
|
||||
|
||||
if ($identifiant === "" || $motDePasse === "")
|
||||
{
|
||||
throw new InvalidArgumentException("Identifiant et mot de passe obligatoires.");
|
||||
}
|
||||
|
||||
if ($this->trouverParIdentifiant($identifiant) !== null)
|
||||
{
|
||||
throw new InvalidArgumentException("Cet identifiant est déjà utilisé.");
|
||||
}
|
||||
|
||||
if (strlen($motDePasse) < 6)
|
||||
{
|
||||
throw new InvalidArgumentException("Le mot de passe doit contenir au moins 6 caractères.");
|
||||
}
|
||||
|
||||
$maintenant = Helpers::maintenant();
|
||||
|
||||
$utilisateur = [
|
||||
"id" => Helpers::genererId(),
|
||||
"identifiant" => $identifiant,
|
||||
"email" => $email,
|
||||
"motDePasseHash" => password_hash($motDePasse, PASSWORD_DEFAULT),
|
||||
"role" => $role === "admin" ? "admin" : "utilisateur",
|
||||
"actif" => true,
|
||||
"createdAt" => $maintenant,
|
||||
"updatedAt" => $maintenant
|
||||
];
|
||||
|
||||
return $this->store->ajouter($utilisateur);
|
||||
}
|
||||
|
||||
public function definirActif(string $id, bool $actif): ?array
|
||||
{
|
||||
return $this->store->mettreAJour($id, [
|
||||
"actif" => $actif,
|
||||
"updatedAt" => Helpers::maintenant()
|
||||
]);
|
||||
}
|
||||
|
||||
public function supprimer(string $id): bool
|
||||
{
|
||||
return $this->store->supprimer($id);
|
||||
}
|
||||
|
||||
public function assurerCompteAdmin(): void
|
||||
{
|
||||
if (count($this->store->tout()) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
$this->creer(
|
||||
Config::get("adminIdentifiant"),
|
||||
Config::get("adminEmail"),
|
||||
Config::get("adminMotDePasse"),
|
||||
"admin"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class View
|
||||
{
|
||||
public static function rendre(string $vue, array $donnees = [], string $layout = "layout"): void
|
||||
{
|
||||
extract($donnees, EXTR_SKIP);
|
||||
|
||||
$cheminVue = dirname(__DIR__) . "/templates/" . $vue . ".php";
|
||||
$cheminLayout = dirname(__DIR__) . "/templates/" . $layout . ".php";
|
||||
|
||||
if (!file_exists($cheminVue))
|
||||
{
|
||||
throw new RuntimeException("Vue introuvable : " . $vue);
|
||||
}
|
||||
|
||||
ob_start();
|
||||
require $cheminVue;
|
||||
$contenu = ob_get_clean();
|
||||
|
||||
require $cheminLayout;
|
||||
}
|
||||
|
||||
public static function partiel(string $vue, array $donnees = []): void
|
||||
{
|
||||
extract($donnees, EXTR_SKIP);
|
||||
require dirname(__DIR__) . "/templates/" . $vue . ".php";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . "/Config.php";
|
||||
require_once __DIR__ . "/JsonStore.php";
|
||||
require_once __DIR__ . "/Csrf.php";
|
||||
require_once __DIR__ . "/Flash.php";
|
||||
require_once __DIR__ . "/Helpers.php";
|
||||
require_once __DIR__ . "/View.php";
|
||||
require_once __DIR__ . "/Auth.php";
|
||||
require_once __DIR__ . "/Router.php";
|
||||
require_once __DIR__ . "/Services/UtilisateurService.php";
|
||||
require_once __DIR__ . "/Services/ConsoleService.php";
|
||||
require_once __DIR__ . "/Services/JeuService.php";
|
||||
require_once __DIR__ . "/Services/EnrichissementService.php";
|
||||
require_once __DIR__ . "/Controllers/AuthController.php";
|
||||
require_once __DIR__ . "/Controllers/AccueilController.php";
|
||||
require_once __DIR__ . "/Controllers/ConsoleController.php";
|
||||
require_once __DIR__ . "/Controllers/JeuController.php";
|
||||
require_once __DIR__ . "/Controllers/AdminController.php";
|
||||
|
||||
Config::charger();
|
||||
|
||||
foreach (["", "/jaquettes", "/cache"] as $sousDossier)
|
||||
{
|
||||
$chemin = Config::get("dataPath") . $sousDossier;
|
||||
|
||||
if (!is_dir($chemin))
|
||||
{
|
||||
mkdir($chemin, 0775, true);
|
||||
}
|
||||
}
|
||||
|
||||
$utilisateurService = new UtilisateurService();
|
||||
$consoleService = new ConsoleService();
|
||||
$jeuService = new JeuService();
|
||||
$enrichissementService = new EnrichissementService();
|
||||
$auth = new Auth($utilisateurService);
|
||||
|
||||
$auth->demarrerSession();
|
||||
$utilisateurService->assurerCompteAdmin();
|
||||
|
||||
$authController = new AuthController($auth, $utilisateurService);
|
||||
$accueilController = new AccueilController($auth, $consoleService, $jeuService);
|
||||
$consoleController = new ConsoleController($auth, $consoleService, $jeuService);
|
||||
$jeuController = new JeuController($auth, $jeuService, $consoleService, $enrichissementService);
|
||||
$adminController = new AdminController($auth, $utilisateurService);
|
||||
|
||||
$router = new Router();
|
||||
|
||||
$router->get("/", [$accueilController, "index"]);
|
||||
|
||||
$router->get("/connexion", [$authController, "connexion"]);
|
||||
$router->post("/connexion", [$authController, "connexion"]);
|
||||
$router->get("/inscription", [$authController, "inscription"]);
|
||||
$router->post("/inscription", [$authController, "inscription"]);
|
||||
$router->post("/deconnexion", [$authController, "deconnexion"]);
|
||||
|
||||
$router->get("/consoles", [$consoleController, "liste"]);
|
||||
$router->get("/consoles/creer", [$consoleController, "creer"]);
|
||||
$router->post("/consoles/creer", [$consoleController, "creer"]);
|
||||
$router->get("/consoles/{id}", [$consoleController, "detail"]);
|
||||
$router->get("/consoles/{id}/modifier", [$consoleController, "modifier"]);
|
||||
$router->post("/consoles/{id}/modifier", [$consoleController, "modifier"]);
|
||||
$router->post("/consoles/{id}/supprimer", [$consoleController, "supprimer"]);
|
||||
|
||||
$router->get("/jeux", [$jeuController, "liste"]);
|
||||
$router->get("/jeux/creer", [$jeuController, "creer"]);
|
||||
$router->post("/jeux/creer", [$jeuController, "creer"]);
|
||||
$router->get("/jeux/api/rechercher", [$jeuController, "rechercherApi"]);
|
||||
$router->post("/jeux/api/appliquer", [$jeuController, "appliquerEnrichissement"]);
|
||||
$router->get("/jeux/{id}", [$jeuController, "detail"]);
|
||||
$router->get("/jeux/{id}/modifier", [$jeuController, "modifier"]);
|
||||
$router->post("/jeux/{id}/modifier", [$jeuController, "modifier"]);
|
||||
$router->post("/jeux/{id}/supprimer", [$jeuController, "supprimer"]);
|
||||
|
||||
$router->get("/admin/utilisateurs", [$adminController, "index"]);
|
||||
$router->post("/admin/utilisateurs/{id}/basculer", [$adminController, "basculerActif"]);
|
||||
$router->post("/admin/utilisateurs/{id}/supprimer", [$adminController, "supprimer"]);
|
||||
|
||||
return $router;
|
||||