You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WF-WEB-API/src/controllers/QuizController.php

85 lines
3.2 KiB

<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class QuizController {
protected $db;
public function __construct($container) {
$this->db = $container->get('db');
}
// Récupérer tous les quiz
public function getQuizzes(Request $request, Response $response, $args) {
$sql = "SELECT * FROM Quiz";
try {
$stmt = $this->db->query($sql);
$quizzes = $stmt->fetchAll(\PDO::FETCH_OBJ);
$payload = json_encode($quizzes);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Récupérer un quiz par son ID
public function getQuiz(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "SELECT * FROM Quiz WHERE id_quiz = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$quiz = $stmt->fetch(\PDO::FETCH_OBJ);
if(!$quiz){
$payload = json_encode(['message' => 'Quiz not found']);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
$payload = json_encode($quiz);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Créer un nouveau quiz
public function createQuiz(Request $request, Response $response, $args) {
$data = $request->getParsedBody();
$sql = "INSERT INTO Quiz (title, img, nb_quest) VALUES (:title, :img, :nb_quest)";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("title", $data['title']);
$stmt->bindParam("img", $data['img']);
$stmt->bindParam("nb_quest", $data['nb_quest']);
$stmt->execute();
$data['id_quiz'] = $this->db->lastInsertId();
$payload = json_encode($data);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Supprimer un quiz
public function deleteQuiz(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "DELETE FROM Quiz WHERE id_quiz = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$payload = json_encode(['message' => 'Quiz deleted']);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
}