From 959b47d2730bf73283365a9db80bda28100c1661 Mon Sep 17 00:00:00 2001 From: beaulaton Date: Thu, 16 Jan 2025 11:41:12 +0100 Subject: [PATCH] Documentation Gateway --- config/config.php | 2 +- src/Gateway/CharacterGateway.php | 117 +++++- src/Gateway/CommentaryGateway.php | 209 ++++++++-- src/Gateway/FavoriteGateway.php | 123 ++++-- src/Gateway/ImageGateway.php | 141 +++++-- src/Gateway/QuestionGateway.php | 174 ++++++-- src/Gateway/QuizGateway.php | 81 +++- src/Gateway/QuizQuestionGateway.php | 64 +-- src/Gateway/QuoteGateway.php | 381 ++++++++++-------- src/Gateway/ResultsGateway.php | 125 ------ src/Gateway/SourceGateway.php | 154 +++++-- src/Gateway/UserGateway.php | 603 ++++++++++++++++++++++------ 12 files changed, 1516 insertions(+), 658 deletions(-) delete mode 100644 src/Gateway/ResultsGateway.php diff --git a/config/config.php b/config/config.php index 2e99e02..836d703 100644 --- a/config/config.php +++ b/config/config.php @@ -14,7 +14,7 @@ $mdp = ''; -$racine='/~kemondejar/WF-Website'; // /~kekentin/WF/WF-Website /~lebeaulato/WF-Website /~kemondejar/WF-Website +$racine='/~lebeaulato/WF-Website'; // /~kekentin/WF/WF-Website /~lebeaulato/WF-Website /~kemondejar/WF-Website //$racine='/WF-Website'; diff --git a/src/Gateway/CharacterGateway.php b/src/Gateway/CharacterGateway.php index 9d4c1b7..b2feb84 100644 --- a/src/Gateway/CharacterGateway.php +++ b/src/Gateway/CharacterGateway.php @@ -8,61 +8,142 @@ use PDO; class CharacterGateway extends Gateway { - public function create(int $id_character, string $name , string $img_char) : bool + /** + * Creates a new character record in the database. + * + * This method inserts a new character into the `caracter` table using the provided character + * ID, name, and image path. + * + * @param int $id_character The unique ID for the character. + * @param string $name The name of the character. + * @param string $img_char The path to the character's image. + * + * @return bool Returns `true` if the character was successfully created, + * or `false` if the insertion failed (e.g., due to a database error). + */ + public function create(int $id_character, string $name, string $img_char) : bool { - $query = " - INSERT INTO caracter - VALUES(:id_caracter, :caracter, :id_img) - "; + // SQL query to insert a new character into the "caracter" table + $query = "INSERT INTO caracter + VALUES(:id_caracter, :caracter, :id_img)"; - return $this -> co -> executeQuery($query, [ + // Execute the query with the provided parameters + return $this->co->executeQuery($query, [ 'id_caracter' => array($id_character, PDO::PARAM_INT), 'caracter' => array($name, PDO::PARAM_STR), 'id_img' => array($img_char, PDO::PARAM_STR) ]); - } + + /** + * Finds a character by its ID in the database. + * + * This method retrieves a character from the `caracter` table by its unique character ID. + * + * @param int $id The unique ID of the character to retrieve. + * + * @return array Returns an array containing the character data if found, or an empty array if no matching character is found. + */ public function findById(int $id) : array { + // SQL query to select a character by its unique ID $query = "SELECT * FROM caracter WHERE id_caracter = :id_c"; - $this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]); - return $this -> co -> getResults(); + + // Execute the query with the provided character ID + $this->co->executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]); + + // Return the results (array of matching character data) + return $this->co->getResults(); } + + /** + * Finds a character by its name in the database. + * + * This method retrieves a character from the `caracter` table by its name. + * + * @param string $name The name of the character to retrieve. + * + * @return array Returns an array containing the character data if found, or an empty array if no matching character is found. + */ public function findByName(string $name) : array { + // SQL query to select a character by its name $query = "SELECT * FROM caracter WHERE caracter = :n"; - $this -> co -> executeQuery($query, ["n" => array($name, PDO::PARAM_STR)]); - return $this -> co -> getResults(); + + // Execute the query with the provided character name + $this->co->executeQuery($query, ["n" => array($name, PDO::PARAM_STR)]); + + // Return the results (array of matching character data) + return $this->co->getResults(); } + + /** + * Retrieves all characters from the database. + * + * This method fetches all rows from the `caracter` table, ordering them by the character name (`caracter`) in ascending order. + * + * @return array Returns an array of all characters. Each character is represented as an associative array with column names as keys. + */ public function findAll() : array { + // SQL query to retrieve all characters from the 'caracter' table, ordered by character name in ascending order $query = "SELECT * FROM caracter ORDER BY caracter ASC"; - $this -> co -> executeQuery($query); - return $this -> co -> getResults(); + + // Execute the query + $this->co->executeQuery($query); + + // Return the results, which is an array of all character records + return $this->co->getResults(); } + + /** + * Deletes a character from the database by its ID. + * + * This method removes a character from the `caracter` table based on the provided character ID (`id_caracter`). + * It executes a DELETE SQL query to remove the record from the database. + * + * @param int $id The ID of the character to be deleted. + * + * @return bool Returns `true` if the deletion was successful, `false` otherwise. + */ public function delete(int $id) : bool { + // SQL query to delete a character from the 'caracter' table by character ID $query = "DELETE FROM caracter WHERE id_caracter = :id_c"; + + // Execute the query using the provided character ID, binding the parameter to an integer return $this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]); } + + /** + * Updates the details of a character in the database. + * + * This method updates a character's name and associated image in the `caracter` table + * based on the provided character ID (`id_caracter`). + * + * @param int $id_char The ID of the character to be updated. + * @param string $name The new name for the character. + * @param string $img_char The new image path for the character. + * + * @return bool Returns `true` if the update was successful, `false` otherwise. + */ public function update(int $id_char, string $name, string $img_char) : bool { - $query = " - UPDATE caracter + // SQL query to update the character's name and image based on character ID + $query = "UPDATE caracter SET caracter = :n, id_img = :i - WHERE id_caracter = :id_c - "; + WHERE id_caracter = :id_c"; + // Execute the query, binding the parameters for character ID, name, and image path return $this -> co -> executeQuery($query, [ "id_c" => array($id_char, PDO::PARAM_INT), "caracter" => array($name, PDO::PARAM_STR), "i" => array($img_char, PDO::PARAM_STR) ]); } - } \ No newline at end of file diff --git a/src/Gateway/CommentaryGateway.php b/src/Gateway/CommentaryGateway.php index 5400543..f395e0d 100644 --- a/src/Gateway/CommentaryGateway.php +++ b/src/Gateway/CommentaryGateway.php @@ -4,70 +4,205 @@ use PDO; class CommentaryGateway extends Gateway{ - public function firstIdComment():int{ - $query = "Select id_comment from Commentary;"; - $this -> co -> executeQuery($query); - $res = $this -> co -> getResults(); + /** + * Finds the first available ID for a new comment in the Commentary table. + * + * This method retrieves all existing comment IDs from the Commentary table, determines the first unused ID, + * and returns it. If there are no comments in the table, it returns `1` as the starting ID. + * + * @return int The first available ID for a new comment. + */ + public function firstIdComment(): int + { + // Define the query to fetch all comment IDs from the Commentary table + $query = "SELECT id_comment FROM Commentary;"; + + // Execute the query and fetch the results + $this->co->executeQuery($query); + $res = $this->co->getResults(); + + // Initialize an array to store existing comment IDs $tab = null; - foreach($res as $r){ + + // Populate the array with IDs from the result set + foreach ($res as $r) { $tab[] = $r["id_comment"]; } - if($tab == null){ + + // If no comments exist, return 1 as the starting ID + if ($tab == null) { return 1; } - $id=1; - while(in_array($id,$tab)){$id=$id+1;} + + // Initialize the ID counter + $id = 1; + + // Increment the ID until a gap is found (i.e., an ID that is not in the array) + while (in_array($id, $tab)) { + $id = $id + 1; + } + + // Return the first available ID return $id; } - public function create(string $comment ,string $idUser, int $idQuote) :bool { - $id=$this->firstIdComment(); - $query="INSERT INTO Commentary(quote,users,datec,comment,id_comment) VALUES(:idQuote, :idUser , CURRENT_DATE,:comment ,:idComment)"; - - return $this -> co -> executeQuery($query, array( + /** + * Creates a new comment in the database. + * + * This method inserts a new comment for a given quote and user into the `Commentary` table. + * It automatically generates a unique comment ID by calling the `firstIdComment()` method. + * + * @param string $comment The text content of the comment. + * @param string $idUser The ID of the user who is posting the comment. + * @param int $idQuote The ID of the quote that the comment is associated with. + * + * @return bool `true` if the comment was successfully created, `false` otherwise. + */ + public function create(string $comment, string $idUser, int $idQuote): bool + { + // Get the first available comment ID using the firstIdComment method + $id = $this->firstIdComment(); + + // Prepare the SQL query to insert a new comment + $query = "INSERT INTO Commentary(quote, users, datec, comment, id_comment) + VALUES(:idQuote, :idUser, CURRENT_DATE, :comment, :idComment)"; + + // Execute the query with the provided parameters + return $this->co->executeQuery($query, array( "comment" => array($comment, PDO::PARAM_STR), "idUser" => array($idUser, PDO::PARAM_STR), "idQuote" => array($idQuote, PDO::PARAM_INT), - "idComment" => array($id, PDO::PARAM_INT))); + "idComment" => array($id, PDO::PARAM_INT) + )); } - public function findById(int $id) : array { - - $query="SELECT * FROM Commentary WHERE id_comment = :id_comment"; - $this -> co -> executeQuery($query, array("id_comment" => $id)); - return $res = $this -> co -> getResults(); + /** + * Retrieves a commentary by its unique ID. + * + * This method queries the `Commentary` table to find a comment by its `id_comment`. + * It returns an array containing the details of the comment if found. + * + * @param int $id The unique ID of the comment to retrieve. + * + * @return array An array containing the commentary details (or an empty array if no comment is found). + */ + public function findById(int $id): array + { + // SQL query to find the commentary by its unique ID + $query = "SELECT * + FROM Commentary + WHERE id_comment = :id_comment"; + + // Execute the query with the provided comment ID as a parameter + $this->co->executeQuery($query, array("id_comment" => $id)); + + // Return the results from the query execution + return $this->co->getResults(); } - public function findByQuote(int $id) : array{ - $query="SELECT c.id_comment, c.dateC, c.comment, u.username, i.imgPath FROM Commentary c JOIN Users u ON u.id_user = c.users JOIN Image i ON i.id_img = u.img WHERE quote = :idQuote ORDER BY c.datec DESC"; - $this -> co -> executeQuery($query, array("idQuote" => array($id,PDO::PARAM_STR))); - return $res = $this -> co -> getResults(); + + /** + * Retrieves all comments associated with a specific quote. + * + * This method queries the `Commentary`, `Users`, and `Image` tables to find all comments related + * to a specific quote, and returns the details of each comment, including the commenter's username, + * the commenter's profile image path, and the comment itself, ordered by date in descending order. + * + * @param int $id The ID of the quote for which comments are being retrieved. + * + * @return array An array containing the details of all comments associated with the specified quote. + * Each entry includes the comment ID, comment date, content, username, and profile image path. + */ + public function findByQuote(int $id): array + { + // SQL query to retrieve comments for a specific quote, joining with the Users and Image tables + $query = "SELECT c.id_comment, c.dateC, c.comment, u.username, i.imgPath + FROM Commentary c + JOIN Users u ON u.id_user = c.users + JOIN Image i ON i.id_img = u.img + WHERE quote = :idQuote + ORDER BY c.datec DESC"; + + // Execute the query with the provided quote ID as a parameter + $this->co->executeQuery($query, array("idQuote" => array($id, PDO::PARAM_STR))); + + // Return the results from the query execution + return $this->co->getResults(); } - public function findAll() : array { - $query="SELECT * FROM Commentary"; - $this -> co -> executeQuery($query); - return $res = $this -> co -> getResults(); - } - public function delete(int $id) : bool { - $query="DELETE FROM Commentary WHERE id_comment = :id_comment"; - return $this -> co -> executeQuery($query, array("id_comment" => $id)); + /** + * Retrieves all comments from the database. + * + * This method executes a query to fetch all records from the `Commentary` table, + * and returns the details of each comment stored in the database. + * + * @return array An array containing all the comments in the `Commentary` table. + * Each entry includes details of the comment, such as the comment's ID, + * creation date, content, user who made the comment, and the quote associated with it. + */ + public function findAll() : array + { + // SQL query to retrieve all comments from the `Commentary` table + $query = "SELECT * FROM Commentary"; + + // Execute the query + $this->co->executeQuery($query); + // Return the results from the query execution + return $this->co->getResults(); } - public function update(commentaryEntity $c) : bool { - $query="UPDATE Commentary SET comment = :comment WHERE id_comment = :id_comment"; + /** + * Deletes a comment from the database. + * + * This method executes a query to delete a specific comment from the `Commentary` table + * based on the provided comment ID. It will remove the comment with the given ID if it exists. + * + * @param int $id The ID of the comment to be deleted. + * + * @return bool Returns `true` if the comment was successfully deleted, + * or `false` if the deletion failed (e.g., if the comment ID was not found). + */ + public function delete(int $id) : bool + { + // SQL query to delete a comment with the specified ID + $query = "DELETE FROM Commentary + WHERE id_comment = :id_comment"; + + // Execute the query and return the result + return $this->co->executeQuery($query, array("id_comment" => $id)); + } - return $this -> co -> executeQuery($query, array( - "comment" => array($c->getComment(),PDO::PARAM_STR), - "id_comment" => array($c->getIdComment(),PDO::PARAM_INT)) - ); + /** + * Updates a comment in the database. + * + * This method executes a query to update the `comment` field of a specific comment in the + * `Commentary` table based on the provided `commentaryEntity` object. It will update the + * comment with the given ID if it exists. + * + * @param commentaryEntity $c The commentary entity containing the new comment content and comment ID. + * + * @return bool Returns `true` if the comment was successfully updated, + * or `false` if the update failed (e.g., if the comment ID was not found). + */ + public function update(commentaryEntity $c) : bool + { + // SQL query to update the comment based on its ID + $query = "UPDATE Commentary + SET comment = :comment + WHERE id_comment = :id_comment"; + + // Execute the query with the parameters from the commentary entity object + return $this->co->executeQuery($query, array( + "comment" => array($c->getComment(), PDO::PARAM_STR), + "id_comment" => array($c->getIdComment(), PDO::PARAM_INT) + )); } } ?> diff --git a/src/Gateway/FavoriteGateway.php b/src/Gateway/FavoriteGateway.php index 495eef4..6fbc59f 100644 --- a/src/Gateway/FavoriteGateway.php +++ b/src/Gateway/FavoriteGateway.php @@ -6,66 +6,139 @@ use PDO; class FavoriteGateway extends Gateway { + /** + * Adds a new favorite entry to the `Favorite` table. + * + * This method inserts a record into the `Favorite` table, linking a user (`idUser`) with + * a specific quote (`idQuote`). It assumes that the `Favorite` table has two columns: + * - `user` (foreign key referencing the user's ID) + * - `quote` (foreign key referencing the quote's ID) + * + * @param int $idUser The ID of the user who is marking the quote as a favorite. + * Must correspond to an existing user in the database. + * @param int $idQuote The ID of the quote being marked as a favorite. + * Must correspond to an existing quote in the database. + * + * @return bool Returns `true` if the query was successfully executed, indicating the favorite + * was added. Returns `false` if the query execution failed. + */ public function createFavoriteGateway(int $idUser, int $idQuote) : bool { - $query = " - INSERT INTO Favorite - VALUES (:user, :quote) - "; + // Define the SQL query to insert a new favorite entry + $query = "INSERT INTO Favorite + VALUES (:user, :quote)"; - return $this -> co -> executeQuery($query, [ + // Execute the query using the provided database connection and return the result + return $this->co->executeQuery($query, [ 'user' => array($idUser, PDO::PARAM_INT), 'quote' => array($idQuote, PDO::PARAM_INT) ]); } + + + /** + * Retrieves a specific favorite entry from the `Favorite` table. + * + * This method fetches a record from the `Favorite` table based on the provided user ID (`idUser`) + * and quote ID (`idQuote`). If the favorite exists, it returns the corresponding data as an array. + * + * @param int $idUser The ID of the user who favorited the quote. This must reference a valid user in the database. + * @param int $idQuote The ID of the quote that is favorited. This must reference a valid quote in the database. + * + * @return array Returns an associative array containing the favorite record if it exists. + * If no matching record is found, an empty array is returned. + */ public function findFavoriteById(int $idUser, int $idQuote) : array { - $query = " - SELECT * FROM Favorite - WHERE user_f = :user AND quote_f = :quote - "; + // Define the SQL query to fetch the favorite record + $query = "SELECT * FROM Favorite + WHERE user_f = :user AND quote_f = :quote"; - $this -> co -> executeQuery($query, [ + // Execute the query using the provided database connection + $this->co->executeQuery($query, [ 'user' => array($idUser, PDO::PARAM_INT), 'quote' => array($idQuote, PDO::PARAM_INT) ]); - return $this -> co -> getResults(); + // Return the query results as an array + return $this->co->getResults(); } + + /** + * Retrieves all favorites for a specific user from the `Favorite` table. + * + * This method fetches all records from the `Favorite` table where the `user_f` column + * matches the provided user ID. It allows retrieving all quotes favorited by a specific user. + * + * @param int $idUser The ID of the user whose favorites are being retrieved. This must reference a valid user in the database. + * + * @return array Returns an array of associative arrays, where each entry represents a favorite record. + * If the user has no favorites, an empty array is returned. + */ public function findFavoriteByUser(int $idUser) : array { - $query = " - SELECT * FROM Favorite - WHERE user_f = :user - "; + // Define the SQL query to fetch all favorites for the user + $query = "SELECT * FROM Favorite + WHERE user_f = :user"; - $this -> co -> executeQuery($query, ['user' => array($idUser, PDO::PARAM_INT)]); + // Execute the query using the provided database connection + $this->co->executeQuery($query, ['user' => array($idUser, PDO::PARAM_INT)]); - return $this -> co -> getResults(); + // Return the query results as an array + return $this->co->getResults(); } + + + /** + * Retrieves all records from the `Favorite` table. + * + * This method fetches all the favorite records in the database, returning an array of + * all user-quote associations stored in the `Favorite` table. + * + * Use this method to get a global view of all user favorites, which can be useful for + * administrative tasks or debugging. + * + * @return array Returns an array of associative arrays where each entry represents a favorite record. + * If there are no records in the table, an empty array is returned. + */ public function findAllFavorite() : array { + // Define the SQL query to fetch all favorite records $query = "SELECT * FROM Favorite"; - $this -> co -> executeQuery($query); + // Execute the query using the provided database connection + $this->co->executeQuery($query); - return $this -> co -> getResults(); + // Return the results of the query as an array + return $this->co->getResults(); } + + /** + * Deletes a specific favorite record from the `Favorite` table. + * + * This method removes the association between a user and a quote in the `Favorite` table + * by matching the provided user ID and quote ID. It is typically used to allow users + * to unfavorite quotes or to clean up favorites. + * + * @param int $idUser The ID of the user whose favorite record is to be deleted. This must reference a valid user in the database. + * @param int $idQuote The ID of the quote to be removed from the user's favorites. This must reference a valid quote in the database. + * + * @return bool Returns `true` if the deletion query was executed successfully, otherwise `false`. + */ public function deleteFavoriteGateway(int $idUser, int $idQuote) : bool { - $query = " - DELETE FROM Favorite - WHERE user_f = :user AND quote_f = :quote - "; + // Define the SQL query to delete a favorite record matching user ID and quote ID + $query = "DELETE FROM Favorite + WHERE user_f = :user AND quote_f = :quote"; - return $this -> co -> executeQuery($query, [ + // Execute the query with the provided parameters + return $this->co->executeQuery($query, [ 'user' => array($idUser, PDO::PARAM_INT), 'quote' => array($idQuote, PDO::PARAM_INT) ]); } - } \ No newline at end of file diff --git a/src/Gateway/ImageGateway.php b/src/Gateway/ImageGateway.php index b001554..6eb2497 100644 --- a/src/Gateway/ImageGateway.php +++ b/src/Gateway/ImageGateway.php @@ -6,61 +6,146 @@ use PDO; class ImageGateway extends Gateway { + /** + * Inserts a new image entry into the `Image` table in the database. + * + * This method executes an SQL query to insert a new record into the `Image` table with the specified image ID + * and image path. It uses the provided database connection to perform the insertion operation. + * + * The image data inserted includes: + * - The image ID (`idImg`). + * - The path to the image file (`imgPath`). + * + * **Note**: This method assumes that the `Image` table exists with at least the `id_img` and `img_path` columns. + * + * @param int $idImg The unique identifier for the image. + * @param string $imgPath The file path to the image (including the filename). + * + * @return bool Returns `true` if the query was successfully executed, `false` if there was an error. + */ public function createImgGateway(int $idImg, string $imgPath) : bool { - $query = " - INSERT INTO Image - VALUES (:id_img, :img_path) - "; + // Define the SQL query to insert a new image record + $query = "INSERT INTO Image + VALUES (:id_img, :img_path)"; - return $this -> co -> executeQuery($query, [ - 'id_img' => array($idImg, PDO::PARAM_INT), - 'img_path' => array($imgPath, PDO::PARAM_STR), + // Execute the query using the provided database connection and parameterized values + return $this->co->executeQuery($query, [ + 'id_img' => array($idImg, PDO::PARAM_INT), // Bind the image ID as an integer + 'img_path' => array($imgPath, PDO::PARAM_STR), // Bind the image path as a string ]); } + + /** + * Finds an image record from the `Image` table by its ID. + * + * This method executes a SQL query to retrieve the image record corresponding to the provided image ID (`$idImg`). + * The method returns all columns of the matching image from the `Image` table. + * + * **Note**: This method assumes that the `Image` table exists with at least the `id_img` and `img_path` columns. + * + * @param int $idImg The unique identifier for the image to retrieve. + * + * @return array Returns an associative array of the image record. The array contains key-value pairs where + * each key is a column name and the value is the corresponding column value from the `Image` table. + * If no matching record is found, it returns an empty array. + */ public function findImgById(int $idImg) : array { - $query = " - SELECT * FROM Image - WHERE id_img = :id_img - "; + // Define the SQL query to select an image by its ID + $query = "SELECT * FROM Image + WHERE id_img = :id_img"; - $this -> co -> executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]); + // Execute the query using the provided database connection and parameterized values + $this->co->executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]); - return $this -> co -> getResults(); + // Return the results of the query execution + return $this->co->getResults(); } + + + /** + * Retrieves all image records from the `Image` table. + * + * This method executes a SQL query to fetch all records from the `Image` table + * and returns the results as an associative array. Each record corresponds to one image. + * + * **Note**: This method assumes that the `Image` table exists with appropriate columns, + * such as `id_img` and `img_path`. + * + * @return array Returns an array of associative arrays, where each associative array represents + * a single image record from the `Image` table. Each key in the associative array + * corresponds to a column name, and the value is the respective column value. + * If no records are found, returns an empty array. + */ public function findAllImg() : array { - $query = " - SELECT * FROM Image - "; + // Define the SQL query to retrieve all image records + $query = "SELECT * FROM Image"; - $this -> co -> executeQuery($query); + // Execute the query using the provided database connection + $this->co->executeQuery($query); - return $this -> co -> getResults(); + // Return the results of the query execution + return $this->co->getResults(); } + + + /** + * Deletes an image record from the `Image` table based on the provided ID. + * + * This method executes a SQL query to delete a specific image record from the database, + * identified by its unique `id_img`. + * + * **Note**: This method assumes that the `Image` table exists and the `id_img` column + * is used as the primary key or a unique identifier for each image. + * + * @param int $idImg The ID of the image to be deleted from the `Image` table. + * Must be a valid integer corresponding to an existing image record. + * + * @return bool Returns `true` if the query was successfully executed, indicating the image + * record was deleted. Returns `false` if the query failed. + */ public function deleteImgGateway(int $idImg) : bool { - $query = " - DELETE FROM Image - WHERE id_img = :id_img - "; + // Define the SQL query to delete an image record based on its ID + $query = "DELETE FROM Image + WHERE id_img = :id_img"; - return $this -> co -> executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]); + // Execute the query using the provided database connection and return the result + return $this->co->executeQuery($query, [ + 'id_img' => array($idImg, PDO::PARAM_INT) + ]); } + + /** + * Updates the path of an image in the `Image` table based on the provided image ID. + * + * This method executes a SQL query to update the `imgPath` column for a specific image + * identified by its unique `id_img`. It assumes the `Image` table exists and contains + * the columns `id_image` and `imgPath`. + * + * @param int $idImg The ID of the image to be updated. Must correspond to an existing + * record in the `Image` table. + * @param string $imgPath The new path for the image. Must be a valid string representing + * the location of the image file. + * + * @return bool Returns `true` if the query was successfully executed, indicating that the + * image path was updated. Returns `false` if the query execution failed. + */ public function updateImgGateway(int $idImg, string $imgPath) : bool { - $query = " - UPDATE Image + // Define the SQL query to update the image path based on the image ID + $query = "UPDATE Image SET imgPath = :img_path - WHERE id_image = :id_img - "; + WHERE id_image = :id_img"; - return $this -> co -> executeQuery($query, [ + // Execute the query using the provided database connection and return the result + return $this->co->executeQuery($query, [ 'id_img' => array($idImg, PDO::PARAM_INT), 'img_path' => array($imgPath, PDO::PARAM_STR) ]); diff --git a/src/Gateway/QuestionGateway.php b/src/Gateway/QuestionGateway.php index d67e175..4711d7c 100644 --- a/src/Gateway/QuestionGateway.php +++ b/src/Gateway/QuestionGateway.php @@ -6,96 +6,196 @@ use PDO; class QuestionGateway extends Gateway { + /** + * Creates a new question entry in the database. + * + * This method inserts a new question into the `Question` table, including the question text, + * multiple choice answers (A, B, C, D), and the correct answer. + * + * @param int $id_question The unique ID of the question. + * @param string $question The question text. + * @param string $answerA The first multiple choice answer. + * @param string $answerB The second multiple choice answer. + * @param string $answerC The third multiple choice answer. + * @param string $answerD The fourth multiple choice answer. + * @param string $cAnswer The correct answer among the options (A, B, C, D). + * + * @return bool Returns `true` if the question was successfully created, `false` otherwise. + */ public function create(int $id_question, string $question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer): bool { - $query = " - INSERT INTO Question - VALUES (:id_q, :question, :answerA, :answerB, :answerC, :answerD, :cAnswer) - "; + // SQL query to insert a new question with its answers and correct answer + $query = "INSERT INTO Question + VALUES (:id_q, :question, :answerA, :answerB, :answerC, :answerD, :cAnswer)"; + // Execute the query, binding the parameters securely to prevent SQL injection return $this -> co -> executeQuery($query, [ - array('id_q' => $id_question, PDO::PARAM_INT), - array('question' => $question, PDO::PARAM_STR), - array('answerA' => $answerA, PDO::PARAM_STR), - array('answerB' => $answerB, PDO::PARAM_STR), - array('answerC' => $answerC, PDO::PARAM_STR), - array('answerD' => $answerD, PDO::PARAM_STR), - array('cAnswer' => $cAnswer, PDO::PARAM_STR), + 'id_q' => array($id_question, PDO::PARAM_INT), + 'question' => array($question, PDO::PARAM_STR), + 'answerA' => array($answerA, PDO::PARAM_STR), + 'answerB' => array($answerB, PDO::PARAM_STR), + 'answerC' => array($answerC, PDO::PARAM_STR), + 'answerD' => array($answerD, PDO::PARAM_STR), + 'cAnswer' => array($cAnswer, PDO::PARAM_STR), ]); } + + /** + * Retrieves a question by its ID from the database. + * + * This method queries the `Question` table to find the question with the specified ID + * and returns all its details, including the question text, possible answers, and the correct answer. + * + * @param int $id The unique ID of the question to be retrieved. + * + * @return array An associative array containing the details of the question (if found). + * The keys correspond to the column names in the `Question` table. + * Returns an empty array if the question is not found. + */ public function findById(int $id) : array { - $query = "SELECT * FROM Question WHERE id_question = :id_q"; + // SQL query to select the question with the specified ID + $query = "SELECT * + FROM Question + WHERE id_question = :id_q"; + + // Execute the query, binding the parameter securely to prevent SQL injection $this -> co -> executeQuery($query, ['id_q' => array($id, PDO::PARAM_INT)]); + + // Retrieve and return the results as an associative array return $this -> co -> getResults(); } + + /** + * Updates the text of a question in the database. + * + * This method modifies the `question` field of a specific question in the `Question` table, + * identified by its unique ID. + * + * @param int $id_q The unique ID of the question to be updated. + * @param string $newQuestion The new text to replace the current question text. + * + * @return bool Returns `true` if the query was successfully executed, or `false` otherwise. + */ public function updateText(int $id_q, string $newQuestion) : bool { - $query = " - UPDATE Question + // SQL query to update the question text for a specific ID + $query = "UPDATE Question SET question = :question - WHERE id_question = :id_q - "; + WHERE id_question = :id_q"; + // Execute the query with bound parameters return $this -> co -> executeQuery($query, [ - 'id_q' => array($id_q, PDO::PARAM_INT), - 'question' => array($newQuestion, PDO::PARAM_STR) + 'id_q' => array($id_q, PDO::PARAM_INT), // Bind the ID of the question + 'question' => array($newQuestion, PDO::PARAM_STR) // Bind the new question text ]); } + + + /** + * Updates the answers for a specific question in the database. + * + * This method modifies the answer options (`answerA`, `answerB`, `answerC`, `answerD`) + * and the correct answer (`cAnswer`) of a specific question identified by its unique ID. + * + * @param int $id_q The unique ID of the question to be updated. + * @param string $newA The new value for the first answer option (A). + * @param string $newB The new value for the second answer option (B). + * @param string $newC The new value for the third answer option (C). + * @param string $newD The new value for the fourth answer option (D). + * @param string $newCorrect The new correct answer. + * + * @return bool Returns `true` if the query was successfully executed, or `false` otherwise. + */ public function updateAnswers(int $id_q, string $newA, string $newB, string $newC, string $newD, string $newCorrect): bool { - $query = " - UPDATE Question + // SQL query to update the answers and the correct answer for a specific question + $query = "UPDATE Question SET answerA = :answerA, answerB = :answerB, answerC = :answerC, answerD = :answerD, cAnswer = :cAnswer - WHERE id_question = :id_q - "; + WHERE id_question = :id_q"; + // Execute the query with bound parameters return $this -> co -> executeQuery($query, [ - 'id_q' => array($id_q, PDO::PARAM_INT), - 'answerA' => array($newA, PDO::PARAM_STR), - 'answerB' => array($newB, PDO::PARAM_STR), - 'answerC' => array($newC, PDO::PARAM_STR), - 'answerD' => array($newD, PDO::PARAM_STR), - 'cAnswer' => array($newCorrect, PDO::PARAM_STR) + 'id_q' => array($id_q, PDO::PARAM_INT), // Bind the ID of the question + 'answerA' => array($newA, PDO::PARAM_STR), // Bind the new answer A + 'answerB' => array($newB, PDO::PARAM_STR), // Bind the new answer B + 'answerC' => array($newC, PDO::PARAM_STR), // Bind the new answer C + 'answerD' => array($newD, PDO::PARAM_STR), // Bind the new answer D + 'cAnswer' => array($newCorrect, PDO::PARAM_STR) // Bind the new correct answer ]); } + /** - * Deletes a question from the database by its ID + * Deletes a question from the database. + * + * This method removes a specific question from the `Question` table based on its unique ID. + * + * @param int $id The unique ID of the question to be deleted. * - * @param int $id The ID of the question - * @return bool + * @return bool Returns `true` if the query was successfully executed, or `false` otherwise. */ public function delete(int $id) : bool { - $query = "DELETE FROM Question WHERE id_question = :id_q"; + // SQL query to delete a question by its ID + $query = "DELETE FROM Question + WHERE id_question = :id_q"; - return $this -> co -> executeQuery($query, ['id_q' => array($id, PDO::PARAM_INT)]); + // Execute the query with the provided ID + return $this -> co -> executeQuery($query, [ + 'id_q' => array($id, PDO::PARAM_INT) // Bind the ID parameter to the query + ]); } + /** - * Retrieves all quizzes from the database + * Retrieves all questions from the database. * - * @return QuestionEntity[] An array of `Question` objects + * This method fetches all records from the `Question` table, returning an array + * of questions with their associated details. + * + * @return array Returns an array containing all the questions. Each question is represented + * as an associative array with keys corresponding to the table columns. */ public function findAll() : array { + // SQL query to select all questions $query = "SELECT * FROM Question"; + + // Execute the query $this -> co -> executeQuery($query); + + // Return all results as an array return $this -> co -> getResults(); } + + /** + * Retrieves a random question from the database. + * + * This method selects one random record from the `Question` table. + * + * @return array Returns an array containing the details of a randomly selected question. + * The result is an associative array with keys corresponding to the table columns. + */ public function findRdmQuestion() : array { - $query = "SELECT * FROM Question ORDER BY RANDOM() LIMIT 1"; + // SQL query to fetch a random question + $query = "SELECT * + FROM Question + ORDER BY RANDOM() + LIMIT 1"; + + // Execute the query $this -> co -> executeQuery($query); + + // Return the randomly selected question return $this -> co -> getResults(); } - } diff --git a/src/Gateway/QuizGateway.php b/src/Gateway/QuizGateway.php index 9bf4ff1..7e1174b 100644 --- a/src/Gateway/QuizGateway.php +++ b/src/Gateway/QuizGateway.php @@ -8,37 +8,98 @@ use PDO; class QuizGateway extends Gateway { + /** + * Creates a new quiz in the database. + * + * This method inserts a new record into the `Quiz` table, specifying the quiz ID + * and the number of questions in the quiz. + * + * @param int $id_quiz The unique ID of the quiz. + * @param int $nb_questions The total number of questions in the quiz. + * + * @return bool Returns `true` if the query was successfully executed, or `false` otherwise. + */ public function create(int $id_quiz, int $nb_questions) : bool { - $query = " - INSERT INTO Quiz - VALUES (:id_q, :nb_q) - "; + // SQL query to insert a new quiz into the Quiz table + $query = "INSERT INTO Quiz + VALUES (:id_q, :nb_q)"; + // Execute the query with bound parameters return $this -> co -> executeQuery($query, [ - ':id_q' => array($id_quiz, PDO::PARAM_INT), - ':nb_q' => array($nb_questions, PDO::PARAM_INT) + ':id_q' => array($id_quiz, PDO::PARAM_INT), // Bind the quiz ID + ':nb_q' => array($nb_questions, PDO::PARAM_INT) // Bind the number of questions ]); } + + /** + * Retrieves a quiz from the database by its ID. + * + * This method fetches a single quiz record from the `Quiz` table, identified by its unique ID. + * + * @param int $id The unique ID of the quiz to retrieve. + * + * @return array Returns an associative array representing the quiz, with keys corresponding + * to the table columns. If no quiz is found, returns an empty array. + */ public function findQuizById(int $id) : array { - $query = "SELECT * FROM Quiz WHERE id_quiz = :id_q"; - $this -> co -> executeQuery($query, [':id_q' => array($id, PDO::PARAM_INT)]); + // SQL query to fetch a quiz by its ID + $query = "SELECT * + FROM Quiz + WHERE id_quiz = :id_q"; + + // Execute the query with the bound ID parameter + $this -> co -> executeQuery($query, [ + ':id_q' => array($id, PDO::PARAM_INT) // Bind the quiz ID + ]); + + // Return the result as an array return $this -> co -> getResults(); } + + /** + * Deletes a quiz from the database by its ID. + * + * This method removes a specific quiz from the `Quiz` table, identified by its unique ID. + * + * @param int $id The unique ID of the quiz to be deleted. + * + * @return bool Returns `true` if the query was successfully executed, or `false` otherwise. + */ public function delete(int $id) : bool { - $query = "DELETE FROM Quiz WHERE id_quiz = :id_q"; - return $this -> co -> executeQuery($query, [':id_q' => array($id, PDO::PARAM_INT)]); + // SQL query to delete a quiz by its ID + $query = "DELETE FROM Quiz + WHERE id_quiz = :id_q"; + + // Execute the query with the provided ID parameter + return $this -> co -> executeQuery($query, [ + ':id_q' => array($id, PDO::PARAM_INT) // Bind the quiz ID + ]); } + + /** + * Retrieves all quizzes from the database. + * + * This method fetches all records from the `Quiz` table, returning an array of results. + * + * @return array Returns an array containing all quizzes. Each quiz is represented as an associative array with its columns as keys. + */ public function findAll() : array { + // SQL query to select all records from the Quiz table $query = "SELECT * FROM Quiz"; + + // Execute the query to fetch all quiz records $this -> co -> executeQuery($query); + + // Return the results retrieved from the database return $this -> co -> getResults(); } + } \ No newline at end of file diff --git a/src/Gateway/QuizQuestionGateway.php b/src/Gateway/QuizQuestionGateway.php index 8ae776e..d098048 100644 --- a/src/Gateway/QuizQuestionGateway.php +++ b/src/Gateway/QuizQuestionGateway.php @@ -6,62 +6,26 @@ use PDO; class QuizQuestionGateway extends Gateway { - public function createQuizQuestionGateway(int $idQuiz, int $idQuestion): bool - { - $query = " - INSERT INTO Quiz_Question - VALUES (:id_quiz, :id_question) - "; - - return $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_question' => array($idQuestion, PDO::PARAM_INT) - ]); - } - - public function findQuizQuestionById(int $idQuiz, int $idQuestion) : array - { - $query = " - SELECT * FROM Quiz_Question - WHERE quiz = :id_quiz AND question_qq = :id_question - "; - - $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_question' => array($idQuestion, PDO::PARAM_INT) - ]); - - return $this -> co -> getResults(); - } - + /** + * Retrieves the questions associated with a specific quiz. + * + * This method fetches all records from the `Quiz_Question` table that are linked to a specific quiz by its ID. + * + * @param int $idQuiz The ID of the quiz for which the questions are to be retrieved. + * + * @return array Returns an array of questions linked to the provided quiz ID. Each question is represented as an associative array with its columns as keys. + */ public function findQuestionsFromQuiz(int $idQuiz) : array { - $query = " - SELECT * FROM Quiz_Question - WHERE quiz = :id_quiz - "; + // SQL query to select all records from the Quiz_Question table where the quiz ID matches the given ID + $query = "SELECT * FROM Quiz_Question + WHERE quiz = :id_quiz"; + // Execute the query with the provided quiz ID $this -> co -> executeQuery($query, ['id_quiz' => array($idQuiz, PDO::PARAM_INT)]); + // Return the results retrieved from the database return $this -> co -> getResults(); } - public function deleteQuizQuestionGateway(int $idQuiz, int $idQuestion) : bool - { - $query = " - DELETE FROM Quiz_Question - WHERE quiz = :id_quiz AND question_qq = :id_question - "; - - return $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_question' => array($idQuestion, PDO::PARAM_INT) - ]); - } - - # To do : - # Method that deletes all questions related to a quiz - - - } \ No newline at end of file diff --git a/src/Gateway/QuoteGateway.php b/src/Gateway/QuoteGateway.php index d5ace1f..55db594 100644 --- a/src/Gateway/QuoteGateway.php +++ b/src/Gateway/QuoteGateway.php @@ -5,87 +5,139 @@ use PDOException; Class QuoteGateway extends Gateway{ - public function searchQuote(string $quote,int $numpage,string $language):array{ - $query="SELECT q.id_quote, q.content, q.id_caracter, c.img_char, s.title, s.date, q.likes, q.langue + /** + * Searches for quotes that match the given criteria (quote content, language, and pagination). + * + * This method retrieves quotes from the `Quote` table that match a specified search term (`$quote`), + * belong to the specified language (`$language`), and are marked as valid. It also supports pagination. + * + * @param string $quote The search term to match within the content of the quotes. + * @param int $numpage The page number to retrieve, used for pagination. This number is used to calculate + * the offset in the query to return results for that specific page. + * @param string $language The language of the quotes to retrieve. + * + * @return array Returns an array of quotes matching the search criteria. Each quote is represented + * as an associative array with column names as keys. + */ + public function searchQuote(string $quote, int $numpage, string $language) : array + { + // SQL query to search for quotes with pagination and language filtering + $query = "SELECT q.id_quote, q.content, q.id_caracter, c.img_char, s.title, s.date, q.likes, q.langue FROM Quote q JOIN Source s ON s.id_source = q.id_source WHERE content LIKE '%:quote%' AND is_valid = true AND langue = :langue LIMIT 20 OFFSET :page*20;"; - $this->co->executeQuery($query,array(':quote' => array($quote,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR))); - return $this->co->getResults(); - } - public function searchSource(string $source,int $numpage,string $language):array{ + // Execute the query with the provided parameters + $this->co->executeQuery($query, [ + ':quote' => array($quote, PDO::PARAM_STR), + ':page' => array($numpage, PDO::PARAM_INT), + ':langue' => array($language, PDO::PARAM_STR) + ]); - //recherche par source - $query="SELECT q.id_quote, q.content, c.character, c.img_path, s.title, s.date, q.likes, q.langue - FROM Quote q - JOIN Caracter c ON c.id_caracter = q.character - JOIN Source s ON s.id_source = q.id_source - WHERE s.title LIKE '%:source%' AND q.is_valid = true AND langue = :langue - LIMIT 20 OFFSET :page*20;"; - $this->co->executeQuery($query,array(':source' => array($source,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR))); - $result=$this->co->getResults(); - return $result; + // Return the search results + return $this->co->getResults(); } - public function searchPers(string $Carac,int $numpage,string $language):array{ - //recherche par personnage - $query="SELECT q.id_quote, q.content, c.character, c.img_path, s.title, s.date, q.likes, q.langue + /** + * Searches for a quote by its unique ID. + * + * This method retrieves a quote from the `Quote` table based on its ID (`$id`). It joins related tables + * (`Caracter`, `Source`, and `Image`) to fetch additional information such as character name, image path, + * source title, and the number of likes, only for valid quotes. + * + * @param string $id The unique identifier of the quote to retrieve. + * + * @return array Returns an associative array of the quote's details including content, character, image path, + * source title, date, likes, and language. + */ + public function searchId(string $id): array + { + // SQL query to search for a quote by its ID with related tables for additional information + $query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue FROM Quote q - JOIN Caracter c ON c.id_caracter = q.character + JOIN Caracter c ON c.id_caracter = q.id_caracter JOIN Source s ON s.id_source = q.id_source - WHERE c.character LIKE '%:pers%' AND q.is_valid = true AND langue = :langue - LIMIT 20 OFFSET :page*20;"; - $this->co->executeQuery($query,array(':pers' => array($Pers,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR))); - $result=$this->co->getResults(); - return $result; + JOIN Image i ON c.id_img = i.id_img + WHERE q.id_quote = :id AND q.isvalide = true;"; + + // Execute the query with the provided quote ID + $this->co->executeQuery($query, [':id' => array($id, PDO::PARAM_STR)]); + + // Return the result set + return $this->co->getResults(); } - public function searchId(string $id):array{ - //recherche par id - $query="SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue + /** + * Searches for quotes based on a search term and filter type. + * + * This method allows you to search for quotes by a specific criterion, such as character name (`personnage`), + * source title (`titre`), or the content of the quote itself. It joins related tables (`Caracter`, `Source`, and `Image`) + * to retrieve additional information such as the character's name, image, source title, and likes. The search is case-insensitive. + * + * @param string|null $type The type of search. Can be: + * - `personnage` to search by character name. + * - `titre` to search by source title. + * - `null` or any other value to search by quote content. + * If not provided or invalid, it defaults to searching by content. + * + * @param string|null $search The search term to look for in the chosen field (`personnage`, `titre`, or `content`). + * This parameter can be `null`, which will result in no filtering. + * + * @param array $filtre (Unused in this method, included for compatibility) + * + * @return array Returns an associative array of quotes matching the search criteria, including content, character name, + * image path, source title, date, likes, and language. + */ + public function search(?string $type, ?string $search, array $filtre): array + { + // Start building the query + $query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue FROM Quote q JOIN Caracter c ON c.id_caracter = q.id_caracter JOIN Source s ON s.id_source = q.id_source JOIN Image i ON c.id_img = i.id_img - WHERE q.id_quote = :id AND q.isvalide = true;"; - $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR))); - $result=$this->co->getResults(); - return $result; - } - - public function search(?string $type,?string $search,array $filtre):array{ - $query="SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue - FROM Quote q - JOIN Caracter c ON c.id_caracter = q.id_caracter - JOIN Source s ON s.id_source = q.id_source - JOIN Image i ON c.id_img = i.id_img - WHERE lower("; - - if($type=='personnage'){ - $query = $query . "c.caracter) LIKE lower('%" . $search . "%')"; - } - elseif($type=='titre'){ - $query = $query . "s.title) LIKE lower('%" . $search . "%')"; + WHERE lower()"; + + // Build the condition based on the $type parameter + if ($type == 'personnage') { + // Search by character name + $query .= "c.caracter) LIKE lower('%" . $search . "%')"; + } elseif ($type == 'titre') { + // Search by source title + $query .= "s.title) LIKE lower('%" . $search . "%')"; + } else { + // Default to searching by quote content + $query .= "q.content) LIKE lower('%" . $search . "%')"; } - else{ - $query = $query . "q.content) LIKE lower('%" . $search . "%')"; - } - /* Categorie a rajouter - foreach($filtre as $fil){ - $query = $query . " AND " . $fil - }*/ - $this->co->executeQuery($query,array()); + // Execute the query + $this->co->executeQuery($query, array()); - $result=$this->co->getResults(); + // Get the results and return them + $result = $this->co->getResults(); return $result; } - public function getQuoteOfTheDay(string $language): array { + + /** + * Retrieves the quote of the day in the specified language. + * + * This method retrieves the quote of the day from the `DailyQuote` table, including associated information such as + * the character's name, image, source title, and the number of likes. The quote is filtered by its validity (`isValide = true`) + * and the language (`$language`). Only one quote is returned, and the most recent valid quote is chosen. + * + * @param string $language The language of the quote to retrieve (e.g., "English", "French", etc.). + * + * @return array Returns an associative array of the quote's details, including the quote content, character, + * character image path, source title, source date, likes, and language. If no result is found, + * an empty array is returned. + */ + public function getQuoteOfTheDay(string $language): array + { + // SQL query to retrieve the quote of the day in the specified language $query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue FROM DailyQuote dq JOIN Quote q ON dq.citation_id = q.id_quote @@ -95,11 +147,16 @@ Class QuoteGateway extends Gateway{ WHERE q.isValide = true AND q.langue = :language ORDER BY q.id_quote DESC LIMIT 1;"; + try { + // Execute the query with the provided language parameter $this->co->executeQuery($query, [':language' => [$language, PDO::PARAM_STR]]); + + // Get the results and return the first (and only) result if available $result = $this->co->getResults(); - return $result[0] ?? []; + return $result[0] ?? []; // Return the first result or an empty array if no result is found } catch (PDOException $e) { + // In case of a database error, catch the exception and display an error message echo "Erreur dans getQuoteOfTheDay: " . $e->getMessage(); return []; } @@ -107,145 +164,141 @@ Class QuoteGateway extends Gateway{ + + /** + * Retrieves a list of quote suggestions in the specified language with pagination. + * + * This method fetches a random selection of quotes that are marked as valid (`isValide = true`) in the specified language. + * The quotes are paginated, returning a set of 20 quotes per page, with each call providing a different set of suggestions + * due to the random ordering. + * + * @param int $numpage The page number for pagination. This value is used to calculate the offset for the query. + * Each page contains 20 quotes. + * + * @param string $language The language of the quotes to retrieve (e.g., "English", "French", etc.). + * + * @return array Returns an array of quotes, each with its content, associated character, character's image path, + * source title, source date, number of likes, and language. If no results are found, an empty array is returned. + */ public function getSuggestions(int $numpage, string $language): array { + // SQL query to retrieve random quote suggestions based on the specified language and pagination $query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue - FROM Quote q - JOIN Caracter c ON c.id_caracter = q.id_caracter - JOIN Source s ON s.id_source = q.id_source - JOIN Image i ON c.id_img = i.id_img - WHERE q.isValide = true AND q.langue = :language - ORDER BY RANDOM() - LIMIT 20 OFFSET :offset;"; + FROM Quote q + JOIN Caracter c ON c.id_caracter = q.id_caracter + JOIN Source s ON s.id_source = q.id_source + JOIN Image i ON c.id_img = i.id_img + WHERE q.isValide = true AND q.langue = :language + ORDER BY RANDOM() + LIMIT 20 OFFSET :offset;"; + // Execute the query with the provided language and offset for pagination $this->co->executeQuery($query, [ ':language' => [$language, PDO::PARAM_STR], - ':offset' => [$numpage * 20, PDO::PARAM_INT] + ':offset' => [$numpage * 20, PDO::PARAM_INT] // Calculate the offset for pagination ]); + + // Return the result set (quotes) return $this->co->getResults(); } + + /** + * Retrieves a list of quotes marked as favorites by a specific user. + * + * This method fetches the quotes that are marked as favorites by the user, along with relevant information such as + * the character's name, image path, source title, and number of likes. It uses the `Favorite` table to identify the quotes + * favorited by the specified user. + * + * @param string $userId The ID of the user whose favorite quotes are to be retrieved. + * + * @return array Returns an array of quotes that are marked as favorites by the user, each with its content, + * associated character, character's image path, source title, source date, likes, and language. + * If no favorites are found, an empty array is returned. + */ public function getFavorites(string $userId): array { + // SQL query to retrieve the list of favorite quotes for a specific user $query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue - FROM Favorite f - JOIN Quote q ON f.quote = q.id_quote - JOIN Caracter c ON c.id_caracter = q.id_caracter - JOIN Source s ON s.id_source = q.id_source - JOIN Image i ON c.id_img = i.id_img - WHERE f.users = :userId"; - + FROM Favorite f + JOIN Quote q ON f.quote = q.id_quote + JOIN Caracter c ON c.id_caracter = q.id_caracter + JOIN Source s ON s.id_source = q.id_source + JOIN Image i ON c.id_img = i.id_img + WHERE f.users = :userId;"; + try { + // Execute the query with the provided user ID $this->co->executeQuery($query, [ ':userId' => [$userId, PDO::PARAM_STR] ]); + + // Return the results (favorites) return $this->co->getResults(); } catch (PDOException $e) { + // In case of a database error, catch the exception and display an error message echo "Erreur dans getFavorites: " . $e->getMessage(); return []; } } - public function autoincrement() : int + + /** + * Retrieves the next available auto-incremented quote ID. + * + * This method retrieves the next available `id_quote` by selecting the maximum `id_quote` in the `Quote` table and + * incrementing it by 1. This value can be used to set the `id_quote` for a new quote being inserted into the database. + * + * @return int Returns the next available quote ID (the maximum `id_quote` value + 1). If no quotes exist yet, it returns 1. + */ + public function autoincrement(): int { - $query = "SELECT Max(id_quote) + 1 as id FROM Quote;"; + // SQL query to retrieve the next available quote ID by selecting the maximum id_quote and adding 1 + $query = "SELECT Max(id_quote) + 1 as id + FROM Quote;"; + + // Execute the query to get the maximum id_quote value $this->co->executeQuery($query); - return ($this -> co ->getResults())[0]['id']; + + // Return the next available id (the result of the query), or 1 if no quotes are found + return ($this->co->getResults())[0]['id']; } + + /** + * Inserts a new quote into the Quote table, associated with a user, source, and character. + * + * This method inserts a new quote into the `Quote` table, setting various attributes like the content, language, + * image path, the user who created the quote, the source of the quote, and the character associated with the quote. + * The method automatically generates a new quote ID by using the `autoincrement` function, ensuring a unique ID + * for each new quote. + * + * @param string $content The content of the quote to be inserted. + * @param string $img_path The path to the image associated with the quote. + * @param string $langage The language of the quote (e.g., "English", "French"). + * @param int $user The ID of the user who created the quote. + * @param int $source The ID of the source of the quote (e.g., book, movie). + * @param int $character The ID of the character associated with the quote. + * + * @return bool Returns true if the query executed successfully, false otherwise. + */ public function insert4User(string $content, string $img_path, string $langage, int $user, int $source, int $character) : bool { - $query = " - INSERT INTO Quote (id_quote, content, langue, reason, id_source, id_caracter, id_user_verif, img_path) - VALUES (:id, :content, :langage, :reason, :source, :character, :user, :img_path) - "; + // SQL query to insert a new quote into the database + $query = "INSERT INTO Quote (id_quote, content, langue, reason, id_source, id_caracter, id_user_verif, img_path) + VALUES (:id, :content, :langage, :reason, :source, :character, :user, :img_path)"; + // Execute the query with the provided parameters return $this->co->executeQuery($query, [ - ':id' => array($this->autoincrement(), PDO::PARAM_INT), - ':content' => array($content, PDO::PARAM_STR), - ':img_path' => array($img_path, PDO::PARAM_STR), - ':langage' => array($langage, PDO::PARAM_STR), - ':user' => array($user, PDO::PARAM_INT), - ':reason' => array('À vérifier', PDO::PARAM_STR), - ':source' => array($source, PDO::PARAM_STR), - ':character' => array($character, PDO::PARAM_STR) + ':id' => array($this->autoincrement(), PDO::PARAM_INT), // Generate the next available quote ID + ':content' => array($content, PDO::PARAM_STR), // Content of the quote + ':img_path' => array($img_path, PDO::PARAM_STR), // Path to the image associated with the quote + ':langage' => array($langage, PDO::PARAM_STR), // Language of the quote + ':user' => array($user, PDO::PARAM_INT), // User ID who created the quote + ':reason' => array('À vérifier', PDO::PARAM_STR), // Default value for the quote verification status + ':source' => array($source, PDO::PARAM_STR), // Source ID (book, movie, etc.) + ':character' => array($character, PDO::PARAM_STR) // Character ID associated with the quote ]); } - //======================== PARTI ADMIN ======================== - //Probablement à déplacer dans un autre fichier - - public function getQuoteIsValide():array{ - //obtenir les quotes en attentes de validation par l'admin - $query = 'SELECT * FROM Quote WHERE isValid=:bool'; - $this->co->executeQuery($query,array(':bool' => array(false, PDO::PARAM_BOOL))); - return $this->co->getResults(); - } - - public function validQuote(int $id){ - //Valider la quote par l'admin - $query ='UPDATE Quote SET isValid=:newValide WHERE id_Quote=:id'; - $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_INT))); - } - - public function invalidQuote(int $id){ - //Invalide la quote par l'admin (suppression) - $query ='DELETE FROM Quote WHERE id_Quote=:id'; - $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_INT))); - } - - public function updateContent(int $id, string $newContent):array{ - //Update le contexte de quote passé en paramètre - $queryUpdate = 'UPDATE Quote SET content=:newContent WHERE id_quote=:idQuote'; - $this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newContent'=> array($newContent, PDO::PARAM_STR))); - - //Renvoie le nouveau contexte de quote - $queryReponse = 'SELECT content FROM Quote WHERE id_quote=:idQuote'; - $this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR))); - return $this->co->getResults(); - } - - public function updateTimeCode(int $id, string $newTimeCode):array{ - //Update le time code de quote passé en paramètre - $queryUpdate = 'UPDATE Quote SET timecode=:newTimeCode WHERE id_quote=:idQuote'; - $this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newTimeCode'=> array($newTimeCode, PDO::PARAM_STR))); - - //Renvoie le nouveau contexte de quote - $queryReponse = 'SELECT timecode FROM Quote WHERE id_quote=:idQuote'; - $this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR))); - return $this->co->getResults(); - } - - public function updateDate(int $id, int $newDate):array{ - //Update la date de quote passé en paramètre - $queryUpdate = 'UPDATE Source SET dateSource =:newdate WHERE idSource = (SELECT idSource FROM Quote WHERE idQuote =:idQuote)'; - $this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newDate'=> array($newDate, PDO::PARAM_INT))); - - //Renvoie la nouvelle date de quote - $queryReponse = 'SELECT s.dateSource FROM Source s, Quote q WHERE id_quote=:idQuote AND s.idSource = q.idSource'; - $this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR))); - return $this->co->getResults(); - } - - public function updateTitle(int $id, string $newTitle):array{ - //Update le titre de l'oeuvre de quote passé en paramètre - $queryUpdate = 'UPDATE Source SET title =:newTitle WHERE idSource = (SELECT idSource FROM Quote WHERE idQuote =:idQuote)'; - $this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newTitle'=> array($newTitle, PDO::PARAM_STR))); - - //Renvoie le nouveau titre de quote - $queryReponse = 'SELECT s.title FROM Source s, Quote q WHERE id_quote=:idQuote AND s.idSource = q.idSource'; - $this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR))); - return $this->co->getResults(); - } - - public function updateNameCharacter(int $id, string $newNameCharacter):array{ - //Update le personnage de l'oeuvre de quote passé en paramètre - $queryUpdate = 'UPDATE Character SET name =:newNameCharacter WHERE idCharacter = (SELECT idCharacter FROM Quote WHERE idQuote =:idQuote)'; - $this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newNameCharacter'=> array($newNameCharacter, PDO::PARAM_STR))); - - //Renvoie le nouveau personnage de quote - $queryReponse = 'SELECT c.title FROM Character c, Quote q WHERE id_quote=:idQuote AND c.idCharacter = q.idCharacter'; - $this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR))); - return $this->co->getResults(); - } } ?> \ No newline at end of file diff --git a/src/Gateway/ResultsGateway.php b/src/Gateway/ResultsGateway.php deleted file mode 100644 index d800fdf..0000000 --- a/src/Gateway/ResultsGateway.php +++ /dev/null @@ -1,125 +0,0 @@ - co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_user' => array($idUser, PDO::PARAM_INT), - 'nb_pts' => array($nbPts, PDO::PARAM_INT), - 'time' => array($time, PDO::PARAM_INT) - ]); - } - - public function findResultsByQuiz(int $idQuiz) : array - { - $query = " - SELECT * FROM Results - WHERE quiz_r = :id_quiz - "; - - $this -> co -> executeQuery($query, ['id_quiz' => array($idQuiz, PDO::PARAM_INT)]); - - return $this -> co -> getResults(); - } - - public function findResultsByUser(int $idUser) : array - { - $query = " - SELECT * FROM Results - WHERE user_r = :id_user - "; - - $this -> co -> executeQuery($query, ['id_user' => array($idUser, PDO::PARAM_INT)]); - - return $this -> co -> getResults(); - } - - public function findResultsById(int $idQuiz, int $idUser) : array - { - $query = " - SELECT * FROM Results - WHERE quiz_r = :id_quiz AND user_r = :id_user - "; - - $this -> co -> executeQuery($query, [ - 'id_user' => array($idUser, PDO::PARAM_INT), - 'id_quiz' => array($idQuiz, PDO::PARAM_INT) - ]); - - return $this -> co -> getResults(); - } - - public function findAllResults() : array - { - $query = "SELECT * FROM Results"; - - $this -> co -> executeQuery($query); - - return $this -> co -> getResults(); - } - - public function updateResults(int $idQuiz, int $idUser, ?int $score, ?int $time) : bool - { - if ($score && !$time) - { - $query = " - UPDATE Results - SET score = :score - WHERE quiz_r = :id_quiz AND user_r = :id_user - "; - - return $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_user' => array($idUser, PDO::PARAM_INT), - 'score' => array($score, PDO::PARAM_INT) - ]); - } - - - else if (!$score && $time) - { - $query = " - UPDATE Results - SET time = :time - WHERE quiz_r = :id_quiz AND user_r = :id_user - "; - - return $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_user' => array($idUser, PDO::PARAM_INT), - 'time' => array($time, PDO::PARAM_INT) - ]); - } - - else - { - $query = " - UPDATE Results - SET score = :score AND time = :time - WHERE quiz_r = :id_quiz AND user_r = :id_user - "; - - return $this -> co -> executeQuery($query, [ - 'id_quiz' => array($idQuiz, PDO::PARAM_INT), - 'id_user' => array($idUser, PDO::PARAM_INT), - 'score' => array($score, PDO::PARAM_INT), - 'time' => array($time, PDO::PARAM_INT) - ]); - } - - } - - -} \ No newline at end of file diff --git a/src/Gateway/SourceGateway.php b/src/Gateway/SourceGateway.php index 402d30b..fe9202a 100644 --- a/src/Gateway/SourceGateway.php +++ b/src/Gateway/SourceGateway.php @@ -6,79 +6,147 @@ use PDO; class SourceGateway extends Gateway{ + /** + * Inserts a new source into the Source table. + * + * This method inserts a new source into the `Source` table, setting attributes like the title and date of the source. + * It takes a `sourceEntity` object as an argument, which contains the data required for the insertion. + * The method assumes that the source entity is valid and contains the appropriate values for the title and date. + * + * @param sourceEntity $s The source entity object containing the source's title and date. + * + * @return bool Returns true if the query executed successfully, false otherwise. + */ public function create(sourceEntity $s) : bool { - $query = " - INSERT INTO Source - VALUES( :title, :date) - "; - - return $this -> co -> executeQuery($query, [ - "title" => array($s->getTitle(), PDO::PARAM_STR), - "date" => array($s->getDate(), PDO::PARAM_STR), - #"type" => array($s->getType(), PDO::PARAM_STR) + // SQL query to insert a new source into the database + $query = "INSERT INTO Source + VALUES( :title, :date)"; + + // Execute the query with the parameters extracted from the source entity object + return $this->co->executeQuery($query, [ + 'title' => array($s->getTitle(), PDO::PARAM_STR), // The title of the source (e.g., book title, movie title) + 'date' => array($s->getDate(), PDO::PARAM_STR), // The date of the source (e.g., publication date, release date) + // 'type' => array($s->getType(), PDO::PARAM_STR) // Optional: Add 'type' if needed (commented out for now) ]); } + /** + * Retrieves a source by its ID from the Source table. + * + * This method fetches the details of a source from the `Source` table by its `id_source`. + * It executes a query to retrieve the source record that matches the provided ID. + * If a source is found with the given ID, the details of the source are returned as an associative array. + * + * @param int $id The ID of the source to be retrieved. + * + * @return array An associative array containing the details of the source, or an empty array if no source is found. + */ public function findById(int $id) : array { - $query = "SELECT * FROM Source WHERE id_source = :id"; + // SQL query to select a source by its ID + $query = "SELECT * + FROM Source + WHERE id_source = :id"; - $this -> co -> executeQuery($query, array("id" => array($id, PDO::PARAM_INT))); - return $res = $this -> co -> getResults(); + // Execute the query with the provided ID + $this->co->executeQuery($query, array("id" => array($id, PDO::PARAM_INT))); + + // Return the result of the query + return $res = $this->co->getResults(); } + + /** + * Retrieves a source by its title from the Source table. + * + * This method fetches the details of a source from the `Source` table by its `title`. + * It executes a query to retrieve the source record that matches the provided title. + * If a source is found with the given title, the details of the source are returned as an associative array. + * + * @param string $t The title of the source to be retrieved. + * + * @return array An associative array containing the details of the source, or an empty array if no source is found. + */ public function findByTitle(string $t) : array { - $query = "SELECT * FROM Source WHERE title = :t"; - $this -> co -> executeQuery($query, ["t" => array($t, PDO::PARAM_STR)]); - return $res = $this -> co -> getResults(); - } + // SQL query to select a source by its title + $query = "SELECT * + FROM Source + WHERE title = :t"; - public function findByDate(string $d) : array - { - $query = "SELECT * FROM Source WHERE dates = :d"; + // Execute the query with the provided title + $this->co->executeQuery($query, ["t" => array($t, PDO::PARAM_STR)]); - $this -> co -> executeQuery($query, ["d" => array($d, PDO::PARAM_STR)]); - return $this -> co -> getResults(); + // Return the result of the query + return $res = $this->co->getResults(); } - - /* - public function findByType(TypeSourceEnum $type) : array - { - $query = "SELECT * FROM Source WHERE type = :t"; - $this -> co -> executeQuery($query, ["t" => array($type, PDO::PARAM_STR)]); - return $this -> co -> getResults(); - } - */ + /** + * Retrieves all sources from the Source table. + * + * This method fetches all records from the `Source` table, sorted by the `title` column in ascending order. + * It executes a query to retrieve all source records and returns them as an associative array. + * + * @return array An array of associative arrays, each containing the details of a source. + */ public function findAll() : array { - $query = "SELECT * FROM Source ORDER BY title ASC"; - $this -> co -> executeQuery($query); - return $this -> co -> getResults(); + // SQL query to select all sources from the Source table, ordered by title in ascending order + $query = "SELECT * + FROM Source + ORDER BY title ASC"; + + // Execute the query to fetch the results + $this->co->executeQuery($query); + + // Return the result of the query + return $this->co->getResults(); } + + /** + * Deletes a source record from the Source table by its ID. + * + * This method deletes the record from the `Source` table where the `id_source` matches the provided ID. + * It executes the DELETE SQL query to remove the source from the database. + * + * @param int $id The ID of the source to delete. + * @return bool True if the delete was successful, false otherwise. + */ public function delete(int $id) : bool { - $query = "DELETE FROM Source WHERE id_source = :id_s"; + // SQL query to delete the source record with the given id_source + $query = "DELETE FROM Source + WHERE id_source = :id_s"; - $this -> co -> executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]); + // Execute the query with the provided source ID + return $this->co->executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]); } + + /** + * Updates an existing source record in the Source table. + * + * This method updates the `title` and `date` columns of the `Source` table for a given `id_source`. + * It executes the `UPDATE` SQL query to modify the record with the specified ID. + * + * @param sourceEntity $s The source entity containing the updated data (ID, title, and date). + * @return bool True if the update was successful, false otherwise. + */ public function update(sourceEntity $s) : bool { - $query = " - UPDATE Source + // SQL query to update the title and date of a source record with the given id_source + $query = "UPDATE Source SET title = :t, date = :d - WHERE id_source = :id_s - "; + WHERE id_source = :id_s"; + + // Execute the query with the provided source entity data return $this->co->executeQuery($query, [ - "id_s" => array($s -> getIdSource(), PDO::PARAM_INT), - "t" => array($s -> getTitle(), PDO::PARAM_STR), - "d" => array($s -> getDate(), PDO::PARAM_STR) + "id_s" => array($s->getIdSource(), PDO::PARAM_INT), + "t" => array($s->getTitle(), PDO::PARAM_STR), + "d" => array($s->getDate(), PDO::PARAM_STR) ]); } - } diff --git a/src/Gateway/UserGateway.php b/src/Gateway/UserGateway.php index ec91f2b..f687e0b 100644 --- a/src/Gateway/UserGateway.php +++ b/src/Gateway/UserGateway.php @@ -4,44 +4,117 @@ use PDO; Class UserGateway extends Gateway{ + /** + * Gets the total number of users in the Users table. + * + * This method executes a `SELECT COUNT(*)` SQL query to count all the records in the `Users` table. + * It returns the count as an array. + * + * @return array An array containing the total number of users in the `Users` table. + */ public function getNumberOfUsers() : array { + // SQL query to count all users in the Users table $query = "SELECT Count(*) FROM Users"; - $this -> co -> executeQuery($query); + // Execute the query + $this->co->executeQuery($query); - return $this -> co -> getResults(); + // Return the result of the query + return $this->co->getResults(); } - public function firstIdUser():int{ - $query = "Select id_user from Users;"; - $this -> co -> executeQuery($query); - $res = $this -> co -> getResults(); - foreach($res as $r){ + + /** + * Finds the first available ID for a new user. + * + * This method fetches all existing user IDs from the `Users` table and + * returns the first integer ID that is not already in use. + * + * @return int The first available user ID. + */ + public function firstIdUser(): int + { + // SQL query to get all user IDs from the Users table + $query = "SELECT id_user FROM Users;"; + + // Execute the query to fetch all user IDs + $this->co->executeQuery($query); + $res = $this->co->getResults(); + + // Initialize an empty array to store the user IDs + foreach ($res as $r) { $tab[] = $r["id_user"]; } - $id=1; - while(in_array($id,$tab)){$id=$id+1;} + + // Start checking for the first available ID from 1 + $id = 1; + while (in_array($id, $tab)) { + // If the ID already exists, increment and check again + $id = $id + 1; + } + + // Return the first available ID return $id; } - public function randomImg():int{ - $query = "SELECT id_img FROM image ORDER BY Random() LIMIT 1"; + + /** + * Fetches a random image ID from the `image` table. + * + * This method selects a random row from the `image` table using the SQL + * clause `ORDER BY RANDOM()` and returns the `id_img` of the randomly selected image. + * + * @return int The ID of a random image. + */ + public function randomImg(): int + { + // SQL query to select a random image ID + $query = "SELECT id_img + FROM image + ORDER BY RANDOM() + LIMIT 1"; + + // Execute the query $this->co->executeQuery($query); + + // Fetch the result $res = $this->co->getResults(); + + // Return the ID of the randomly selected image return $res[0][0]; } - public function insertUser(string $pseudo, string $email, string $password, bool $isAdmin, int $imgPrfl) : bool { - - $id=$this->firstIdUser(); - $idImg=$this->randomImg(); - - $query = " - INSERT INTO Users(id_user,username,email,password,creation,img) - VALUES (:id, :pseudo, :email, :password, CURRENT_DATE, :imgPrfl); - "; - return $this -> co -> executeQuery($query, [ + + /** + * Inserts a new user into the `Users` table. + * + * This method first generates a new user ID, retrieves a random image ID, + * and inserts the provided user details (pseudo, email, password, profile image) + * into the `Users` table. + * + * @param string $pseudo The username (pseudo) of the new user. + * @param string $email The email address of the new user. + * @param string $password The password for the new user. + * @param bool $isAdmin Whether the user is an admin (not used in this query). + * @param int $imgPrfl The ID of the profile image for the new user (assigned randomly). + * + * @return bool Whether the insertion was successful. + */ + public function insertUser(string $pseudo, string $email, string $password, bool $isAdmin, int $imgPrfl): bool + { + // Get the next available user ID using the firstIdUser method + $id = $this->firstIdUser(); + + // Get a random image ID using the randomImg method + $idImg = $this->randomImg(); + + // SQL query to insert the new user into the Users table + $query = "INSERT INTO Users(id_user, username, email, password, creation, img) + VALUES (:id, :pseudo, :email, :password, CURRENT_DATE, :imgPrfl);"; + + // Execute the query with the provided data + return $this->co->executeQuery($query, [ ":id" => [$id, PDO::PARAM_INT], ":pseudo" => [$pseudo, PDO::PARAM_STR], ":email" => [$email, PDO::PARAM_STR], @@ -50,187 +123,477 @@ Class UserGateway extends Gateway{ ]); } - public function delete(string $id) : bool{ - // supretion user - $query='DELETE FROM Users WHERE id_user = :id;'; - return $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR))); + /** + * Deletes a user from the `Users` table. + * + * This method takes a user ID (as a string) and removes the corresponding + * user from the `Users` table using the provided ID. + * + * @param string $id The ID of the user to be deleted. + * @return bool Whether the deletion was successful. + */ + public function delete(string $id): bool + { + // SQL query to delete a user from the Users table based on the user ID + $query = 'DELETE FROM Users + WHERE id_user = :id;'; + + // Execute the query with the provided user ID + return $this->co->executeQuery($query, [ + ':id' => [$id, PDO::PARAM_STR] + ]); } - public function inFavorite(string $username, int $idq):bool{ - $query = 'SELECT count(*) FROM Favorite f JOIN Users u ON f.users = u.id_user WHERE u.username = :user AND f.quote = :id'; - $this->co->executeQuery($query, array(':user'=>array($username, PDO::PARAM_STR),':id'=>array($idq, PDO::PARAM_INT))); + + /** + * Checks if a quote is in the user's favorite list. + * + * This method checks if a specific quote, identified by its ID, + * is already marked as a favorite by a user, identified by their username. + * + * @param string $username The username of the user. + * @param int $idq The ID of the quote. + * @return bool True if the quote is in the user's favorite list, false otherwise. + */ + public function inFavorite(string $username, int $idq): bool + { + // SQL query to count the number of favorites for the given user and quote + $query = 'SELECT count(*) + FROM Favorite f + JOIN Users u ON f.users = u.id_user + WHERE u.username = :user AND f.quote = :id'; + + // Execute the query with the provided parameters (username and quote ID) + $this->co->executeQuery($query, array( + ':user' => array($username, PDO::PARAM_STR), + ':id' => array($idq, PDO::PARAM_INT) + )); + + // Fetch the results and check if count is greater than or equal to 1 $result = $this->co->getResults(); + + // Return true if the quote is in the favorites, otherwise false return ($result[0]['count'] >= 1); } - public function addFavorite(string $username, int $id){ - $query = 'INSERT INTO Favorite VALUES ((SELECT id_user FROM Users WHERE username = :username), :id)'; - $this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR), ':id' => array($id,PDO::PARAM_INT))); + + + /** + * Adds a quote to a user's favorite list and increments the like count for the quote. + * + * This method performs two actions: + * 1. Adds the quote (identified by its ID) to the user's favorite list. + * 2. Increments the number of likes for the given quote. + * + * @param string $username The username of the user who is adding the quote to their favorites. + * @param int $id The ID of the quote being added to the favorites. + */ + public function addFavorite(string $username, int $id) + { + // First query: Insert a new favorite for the user and the specified quote. + $query = 'INSERT INTO Favorite VALUES ( + (SELECT id_user FROM Users WHERE username = :username), + :id + )'; + + // Execute the query to add the quote to the user's favorites + $this->co->executeQuery($query, array( + ':username' => array($username, PDO::PARAM_STR), + ':id' => array($id, PDO::PARAM_INT) + )); + + // Second query: Increment the likes for the given quote. $query = 'UPDATE Quote SET likes = (likes + 1) WHERE id_quote = :id'; - $this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT))); + + // Execute the query to update the like count for the quote + $this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT))); } - public function supFavorite(string $username, int $id){ - $query = 'SELECT id_user FROM Users WHERE username = :username'; - $this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR))); + + /** + * Removes a quote from a user's favorite list and decrements the like count for the quote. + * + * This method performs two actions: + * 1. Removes the specified quote from the user's favorites. + * 2. Decrements the number of likes for the given quote. + * + * @param string $username The username of the user who is removing the quote from their favorites. + * @param int $id The ID of the quote being removed from the favorites. + */ + public function supFavorite(string $username, int $id) + { + // First query: Get the user id based on the username. + $query = 'SELECT id_user + FROM Users + WHERE username = :username'; + $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR))); $result = $this->co->getResults()[0]['id_user']; - $query = 'DELETE FROM Favorite WHERE users = :user AND quote = :id;'; - $this->co->executeQuery($query, array(':user' => array($result,PDO::PARAM_INT), ':id' => array($id,PDO::PARAM_INT))); - $query = 'UPDATE Quote SET likes = (likes - 1) WHERE id_quote = :id'; - $this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT))); + // Second query: Delete the quote from the user's favorites. + $query = 'DELETE FROM Favorite + WHERE users = :user AND quote = :id;'; + $this->co->executeQuery($query, array(':user' => array($result, PDO::PARAM_INT), ':id' => array($id, PDO::PARAM_INT))); + + // Third query: Decrement the like count for the quote. + $query = 'UPDATE Quote + SET likes = (likes - 1) + WHERE id_quote = :id'; + $this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT))); } - public function deleteAllCommentaryUser(string $user){ - $query = 'DELETE FROM Commentary WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);'; - $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR))); + + // ===================== DELETE FUNCTION ===================== + + /** + * Deletes all commentaries made by a user. + * + * This method performs the following actions: + * 1. Finds all commentaries made by a specified user using their username. + * 2. Deletes all the commentaries associated with that user from the Commentary table. + * + * @param string $user The username of the user whose commentaries need to be deleted. + */ + public function deleteAllCommentaryUser(string $user) + { + // Query to delete all commentaries made by the user. + $query = 'DELETE FROM Commentary + WHERE users IN ( SELECT id_user + FROM Users + WHERE username = :user);'; + + // Execute the query with the provided username. + $this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR))); } + - public function deleteAllFavoriteUser(string $user){ - $query = 'DELETE FROM Favorite WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);'; - $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR))); + /** + * Deletes all favorites associated with a user. + * + * This method performs the following actions: + * 1. Finds all favorite quotes associated with the user using their username. + * 2. Deletes all the entries in the Favorite table where this user is marked as the owner. + * + * @param string $user The username of the user whose favorites need to be deleted. + */ + public function deleteAllFavoriteUser(string $user) + { + // Query to delete all favorites associated with the user. + $query = 'DELETE FROM Favorite + WHERE users IN ( SELECT id_user + FROM Users + WHERE username = :user);'; + + // Execute the query with the provided username. + $this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR))); } - public function deleteUser(string $user){ - $query = 'DELETE FROM Users WHERE username=:user;'; - $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR))); - } - // ===================== GET FUNCTION ===================== + /** + * Deletes a user from the Users table based on their username. + * + * @param string $user The username of the user to be deleted. + */ + public function deleteUser(string $user) + { + // SQL query to delete the user from the Users table based on their username. + $query = 'DELETE FROM Users + WHERE username = :user;'; + + // Execute the query with the username parameter. + $this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR))); + } - public function getFavorite(string $id):array{ - //obtention favoris d'un user - $query='SELECT * FROM Quote WHERE id_quote IN (SELECT id_quote FROM Favorite f JOIN users u ON u.id_user = f.user_f WHERE u.id_user = :id);'; - $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR))); - $result=$this->co->getResults(); - return $result; - } + // ===================== GET FUNCTION ===================== - public function getIdUser(string $username):array{ - $query = 'SELECT id_user FROM Users WHERE username=:username'; - $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR))); + /** + * Retrieves the favorite quotes of a user based on their user ID. + * + * @param string $id The ID of the user whose favorite quotes are to be fetched. + * @return array The list of favorite quotes of the user. + */ + public function getFavorite(string $id): array + { + // SQL query to retrieve all quotes that the user has marked as favorites. + $query = 'SELECT * + FROM Quote + WHERE id_quote IN (SELECT id_quote + FROM Favorite f JOIN Users u ON u.id_user = f.user_f + WHERE u.id_user = :id);'; + + // Execute the query with the user ID as a parameter. + $this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_STR))); + + // Get the results of the query and return them. $result = $this->co->getResults(); return $result; } - // ===================== FIND FUNCTION ===================== - //obtenir les information d'un user - public function findDataUser(int $id):array{ - $query = 'SELECT u.id_user , u.username , u.email , u.password , i.imgPath , u.creation FROM Users WHERE id_user=:idUser'; - $this->co->executeQuery($query, array(':idUser'=>array($id, PDO::PARAM_STR))); + /** + * Retrieves the user ID based on the given username. + * + * @param string $username The username for which to retrieve the user ID. + * @return array The user ID corresponding to the given username. + */ + public function getIdUser(string $username): array + { + // SQL query to retrieve the user ID based on the username. + $query = 'SELECT id_user + FROM Users + WHERE username = :username'; + + // Execute the query with the provided username parameter. + $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR))); + + // Get the results of the query and return them. $result = $this->co->getResults(); return $result; } - // obtenir les informations d'un user selon son pseudo - public function findUsername(string $username):array{ - $query = 'SELECT * FROM Users u Join Image i on i.id_img=u.img WHERE username= :username'; - $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR))); + + // ===================== FIND FUNCTION ===================== + + /** + * Retrieves user information including their image based on the username. + * + * @param string $username The username of the user whose details are to be fetched. + * @return array An array containing user details and image information. + */ + public function findUsername(string $username): array + { + // SQL query to retrieve user details and their associated image. + $query = 'SELECT * FROM Users u + JOIN Image i ON i.id_img = u.img + WHERE username = :username'; + + // Execute the query with the provided username as a parameter. + $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR))); + + // Get the result of the query and return it. return $this->co->getResults(); } - public function findEmail(string $email):array{ - $query = 'SELECT * FROM Users WHERE email = :email'; - $this->co->executeQuery($query, array(':email'=>array($email, PDO::PARAM_STR))); + + /** + * Retrieves user information based on their email. + * + * @param string $email The email of the user whose details are to be fetched. + * @return array An array containing the user's details. + */ + public function findEmail(string $email): array + { + // SQL query to retrieve user details based on email. + $query = 'SELECT * + FROM Users + WHERE email = :email'; + + // Execute the query with the provided email as a parameter. + $this->co->executeQuery($query, array(':email' => array($email, PDO::PARAM_STR))); + + // Get the result of the query and return it. return $this->co->getResults(); } + // ===================== CHECK FUNCTION ===================== - public function IsExisteUsername(string $username): bool { - $query = 'SELECT COUNT(*) as count FROM Users WHERE username = :username'; + /** + * Checks if a username already exists in the database. + * + * @param string $username The username to check. + * @return bool Returns true if the username exists, false otherwise. + */ + public function IsExisteUsername(string $username): bool + { + // SQL query to check if the username exists in the "Users" table. + $query = 'SELECT COUNT(*) as count + FROM Users + WHERE username = :username'; + + // Execute the query, binding the provided username parameter. $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR))); + + // Get the query results. $results = $this->co->getResults(); - return $results[0]['count'] > 0; // retourne true si "count" > 0) + // Return true if the "count" is greater than 0, meaning the username exists. + return $results[0]['count'] > 0; } - public function IsExisteEmail(string $email): bool { - $query = 'SELECT COUNT(*) as count FROM Users WHERE email = :email'; + + /** + * Checks if an email already exists in the database. + * + * @param string $email The email to check. + * @return bool Returns true if the email exists, false otherwise. + */ + public function IsExisteEmail(string $email): bool + { + // SQL query to check if the email exists in the "Users" table. + $query = 'SELECT COUNT(*) as count + FROM Users + WHERE email = :email'; + + // Execute the query, binding the provided email parameter. $this->co->executeQuery($query, array(':email' => array($email, PDO::PARAM_STR))); + + // Get the query results. $results = $this->co->getResults(); - return $results[0]['count'] > 0; // retourne true si "count" > 0) + // Return true if the "count" is greater than 0, meaning the email exists. + return $results[0]['count'] > 0; } + + /** + * Retrieves the password hash for a given username. + * + * @param string $username The username to search for. + * @return string|null The password hash if the username is found, null otherwise. + */ public function getPasswordHash(string $username): ?string { - $query = 'SELECT password FROM Users WHERE username = :username'; + // SQL query to retrieve the password hash for a given username. + $query = 'SELECT password + FROM Users + WHERE username = :username'; + + // Execute the query with the provided username as the parameter. $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR))); + + // Get the results of the query. $results = $this->co->getResults(); - - // Si un utilisateur est trouvé, retourner le hash du mot de passe, sinon null + + // If results are found, return the password hash, otherwise return null. return $results ? $results[0]['password'] : null; } + // ===================== UPDATE FUNCTION ===================== - //Update Username - public function updateUsername(string $username, string $newUsername):array{ - //Update le nom du user passé en paramètre - $queryUpdate = 'UPDATE Users SET username=:newUsername WHERE username=:username'; - $this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newUsername'=> array($newUsername, PDO::PARAM_STR))); - - //Renvoie le nouveau nom du user + /** + * Updates the username for a user. + * + * @param string $username The current username. + * @param string $newUsername The new username to set. + * @return array The result of the update, including the new username. + */ + public function updateUsername(string $username, string $newUsername): array { + // SQL query to update the username for the user with the current username + $queryUpdate = 'UPDATE Users + SET username=:newUsername + WHERE username=:username'; + + // Execute the update query with the provided parameters + $this->co->executeQuery($queryUpdate, array( + ':username' => array($username, PDO::PARAM_STR), + ':newUsername' => array($newUsername, PDO::PARAM_STR) + )); + + // SQL query to retrieve the updated username from the Users table $queryReponse = 'SELECT username FROM Users WHERE username=:idUser'; - - $this->co->executeQuery($queryReponse, array(':idUser'=>array($newUsername, PDO::PARAM_STR))); + + // Execute the query to fetch the updated username + $this->co->executeQuery($queryReponse, array(':idUser' => array($newUsername, PDO::PARAM_STR))); + + // Return the result, which will contain the new username return $this->co->getResults(); } - //Update Email - public function updateEmail(string $username, string $newEmail):array{ - //Update le email du user passé en paramètre - $queryUpdate = 'UPDATE Users SET email=:newEmail WHERE username=:username'; - $this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newEmail'=> array($newEmail, PDO::PARAM_STR))); - //Renvoie le nouveau email du user + /** + * Updates the email for a user based on their username. + * + * @param string $username The username of the user whose email will be updated. + * @param string $newEmail The new email to set for the user. + * @return array The result of the update, including the new email. + */ + public function updateEmail(string $username, string $newEmail): array { + // SQL query to update the email for the user with the specified username + $queryUpdate = 'UPDATE Users + SET email=:newEmail + WHERE username=:username'; + + // Execute the update query with the provided parameters (username and newEmail) + $this->co->executeQuery($queryUpdate, array( + ':username' => array($username, PDO::PARAM_STR), + ':newEmail' => array($newEmail, PDO::PARAM_STR) + )); + + // SQL query to retrieve the updated email from the Users table $queryReponse = 'SELECT email FROM Users WHERE username=:username'; - - $this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR))); + + // Execute the query to fetch the updated email + $this->co->executeQuery($queryReponse, array(':username' => array($username, PDO::PARAM_STR))); + + // Return the result, which will contain the new email return $this->co->getResults(); } - public function updateImg(string $username,string $newImage):array{ - if($newImage==null){ + + /** + * Updates the profile image for a user based on their username. + * + * @param string $username The username of the user whose image will be updated. + * @param string|null $newImage The new image ID or `null` to use a random image. + * @return array The result of the update, including the new image ID. + */ + public function updateImg(string $username, string $newImage): array { + // Determine the image ID to use + if ($newImage == null) { + // If no image provided, use a random image ID $id_image = $this->randomImg(); - } - else if(is_int((int)$newImage)){ - $id_image=(int)$newImage; - } - else{ + } else if (is_int((int)$newImage)) { + // If a valid image ID is provided, use it + $id_image = (int)$newImage; + } else { + // If the provided value is not valid, use a random image ID $id_image = $this->randomImg(); } + // SQL query to update the image for the user with the specified username + $query = 'UPDATE Users + SET img=:id_image + WHERE username=:username'; + $this->co->executeQuery($query, array( + ':username' => array($username, PDO::PARAM_STR), + ':id_image' => array($id_image, PDO::PARAM_INT) + )); - //Update l'image du user passé en paramètre - $query = 'UPDATE Users SET img=:id_image WHERE username=:username'; - $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':id_image'=> array($id_image, PDO::PARAM_INT))); - - //Renvoie la nouvelle image du user + // SQL query to retrieve the updated image for the user $queryReponse = 'SELECT img FROM Users WHERE username=:username'; - $this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR))); + $this->co->executeQuery($queryReponse, array(':username' => array($username, PDO::PARAM_STR))); + + // Return the result, which will contain the new image ID return $this->co->getResults(); } - public function updatePasswd(string $username, string $newPassWd):void{ - //Update le passwd du user passé en paramètre - $query = 'UPDATE Users SET password=:newPassWd WHERE username=:username'; - $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':newPassWd'=> array($newPassWd, PDO::PARAM_STR))); - } - public function emailWithUser(string $user):array{ - $query = 'SELECT email FROM Users WHERE username = :user'; - $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR))); - return $this->co->getResults(); + /** + * Updates the password for a user based on their username. + * + * @param string $username The username of the user whose password will be updated. + * @param string $newPassWd The new password to set for the user. + */ + public function updatePasswd(string $username, string $newPassWd): void { + // SQL query to update the password for the user with the specified username + $query = 'UPDATE Users + SET password=:newPassWd + WHERE username=:username'; + + // Execute the query with the provided parameters (username and new password) + $this->co->executeQuery($query, array( + ':username' => array($username, PDO::PARAM_STR), + ':newPassWd' => array($newPassWd, PDO::PARAM_STR) + )); } + } ?>