From 802b9b3c8601fb471860d6ae6121ba457494829f Mon Sep 17 00:00:00 2001
From: SofianeLasri <alasri250@gmail.com>
Date: Sat, 26 Nov 2022 13:14:58 +0100
Subject: [PATCH] =?UTF-8?q?TP7=20-=20Modification=20d'un=20objet=20termin?=
 =?UTF-8?q?=C3=A9e.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 controller/ControleurAdherent.php             |  4 +-
 controller/ControleurAuteur.php               |  4 +-
 controller/ControleurLivre.php                |  4 +-
 controller/ControleurObjet.php                | 95 ++++++++++++++++---
 models/Objet.php                              | 12 ++-
 resources/views/data-grid.php                 |  2 +-
 .../views/formulaire-modification-objet.php   | 30 ++++++
 resources/views/sql-result.php                | 17 ++++
 8 files changed, 146 insertions(+), 22 deletions(-)
 create mode 100644 resources/views/formulaire-modification-objet.php
 create mode 100644 resources/views/sql-result.php

diff --git a/controller/ControleurAdherent.php b/controller/ControleurAdherent.php
index c8611b0..1851ceb 100644
--- a/controller/ControleurAdherent.php
+++ b/controller/ControleurAdherent.php
@@ -15,8 +15,8 @@ class ControleurAdherent extends ControleurObjet
         $adherents = Adherent::getAllAdherents();
         $objects = [];
         foreach ($adherents as $adherent){
-            $object['id_name'] = "login";
-            $object['id_value'] = $adherent->login;
+            $object['idName'] = "login";
+            $object['idValue'] = $adherent->login;
             $object['type'] = "Adherent";
             $object['title'] = $adherent->prenomAdherent . " " . $adherent->nomAdherent;
             $object['desc'] = "ID: $adherent->login<br>Date d'adhésion: {$adherent->dateAdhesion->format("Y-m-d")}";
diff --git a/controller/ControleurAuteur.php b/controller/ControleurAuteur.php
index eddce32..5bbaa7e 100644
--- a/controller/ControleurAuteur.php
+++ b/controller/ControleurAuteur.php
@@ -16,8 +16,8 @@ class ControleurAuteur extends ControleurObjet
 
         $objects = [];
         foreach ($auteurs as $auteur){
-            $object['id_name'] = "numAuteur";
-            $object['id_value'] = $auteur->numAuteur;
+            $object['idName'] = "numAuteur";
+            $object['idValue'] = $auteur->numAuteur;
             $object['type'] = "Auteur";
             $object['title'] = $auteur->prenom . " " . $auteur->nom;
             $object['desc'] = "ID: $auteur->numAuteur<br>Date de naissance: $auteur->anneeNaissance";
diff --git a/controller/ControleurLivre.php b/controller/ControleurLivre.php
index f3c14a4..e70b702 100644
--- a/controller/ControleurLivre.php
+++ b/controller/ControleurLivre.php
@@ -16,8 +16,8 @@ class ControleurLivre extends ControleurObjet
 
         $objects = [];
         foreach ($livres as $livre){
-            $object['id_name'] = "numLivre";
-            $object['id_value'] = $livre->numLivre;
+            $object['idName'] = "numLivre";
+            $object['idValue'] = $livre->numLivre;
             $object['type'] = "Livre";
             $object['title'] = $livre->titre;
             $object['desc'] = "ID: $livre->numLivre<br>Année de parution: $livre->anneeParution";
diff --git a/controller/ControleurObjet.php b/controller/ControleurObjet.php
index a97605d..c9f7812 100644
--- a/controller/ControleurObjet.php
+++ b/controller/ControleurObjet.php
@@ -6,20 +6,20 @@ class ControleurObjet
      * Affiche la page de cration d'un objet et se charge également de sa création.
      * @return string
      */
-    public static function createObject() : string
+    public static function createObject(): string
     {
         $createdObject = [];
         // Si reçoie une requête POST pour créer un objet et qu'on a plus d'une entrée
-        if(!empty($_POST["objectName"]) && count($_POST) > 1){
+        if (!empty($_POST["objectName"]) && count($_POST) > 1) {
             $columns = [];
-            foreach ($_POST as $index => $value){
-                if(!in_array($index, ["action", "objectName"])){
+            foreach ($_POST as $index => $value) {
+                if (!in_array($index, ["action", "objectName"])) {
                     $columns[$index] = $value;
                 }
             }
 
             $createdObject = Objet::addObject($_POST["objectName"], $columns);
-            if($createdObject["status"] === "fail"){
+            if ($createdObject["status"] === "fail") {
                 $createdObject["status"] = "danger"; // Pour le style Bootstrap
             }
         }
@@ -34,9 +34,9 @@ class ControleurObjet
      * Retourne une liste JSON de la description de la table
      * @return string
      */
-    public static function describeTable() : string
+    public static function describeTable(): string
     {
-        if(!empty($_GET["tableName"])){
+        if (!empty($_GET["tableName"])) {
             return json_encode(Objet::describeObject($_GET["tableName"]));
         } else {
             return json_encode([
@@ -47,13 +47,84 @@ class ControleurObjet
         }
     }
 
-    public static function modifyObject() : string
+    public static function modifyObject(): string
     {
-        if(!empty($_GET["tableName"]) && !empty($_GET["id_name"]) && !empty($_GET["id_value"])){
+        if (!empty($_GET["tableName"]) && !empty($_GET["idName"]) && !empty($_GET["idValue"])) {
+            $object = Objet::getObject($_GET["tableName"], ['name' => $_GET["idName"], 'value' => $_GET["idValue"]]);
+            $ojectTableDesc = Objet::describeObject($_GET["tableName"]);
+
+            $sqlToInputType = [
+                "int" => "number",
+                "varchar" => "text",
+                "date" => "date"
+            ];
+
+            $properties = [];
+            foreach ($ojectTableDesc['columns'] as $column) {
+                // On vérifie que la colonne en question n'est pas une clé primaire
+                // Et qu'elle ne possède pas l'indicateur d'interdiction de modification "%!update%" en commentaire
+                if ($column['Key'] !== "PRI" && !in_array("%!update%", explode(',', $column["Comment"]))) {
+                    $input["name"] = $column["Field"];
+
+                    // Ici on transforme la CamelCase en Camel case
+                    $input["showName"] = ucfirst(
+                        strtolower(
+                            join(' ',
+                                preg_split(
+                                    '/(?=[A-Z])/',
+                                    $column["Field"])
+                            )
+                        )
+                    );
+
+                    // Ici on va associer varchar(x) = text, etc.
+                    preg_match("/([a-z]*)/", $column["Type"], $sqlTypeMatch);
+                    $input["type"] = $sqlToInputType[$sqlTypeMatch[0]];
+                    $input["value"] = $object["data"][$column["Field"]];
+
+                    // Ici on va rechercher un potentiel commentaire qui ne serait pas un indicateur
+                    $input["comment"] = "";
+                    $comments = explode(',', $column["Comment"]);
+                    foreach ($comments as $comment) {
+                        preg_match("/(^[^%].*[^%]$)/", $comment, $commentMatch);
+                        if (!empty($commentMatch)) {
+                            $input["comment"] = $commentMatch[0];
+                        }
+                    }
+
+                    $properties[] = $input;
+                }
+            }
 
-            $object = Objet::getObject($_GET["tableName"], ['name' => $_GET["id_name"], 'value' => $_GET["id_value"]]);
-            return json_encode($object);
+            return view('formulaire-modification-objet', [
+                'pageTitle' => "Modifier un(e) {$_GET["tableName"]}",
+                'pageContent' => "Il manque des paramètres dans l'url.",
+                'properties' => $properties
+            ]);
+        } elseif(!empty($_POST["tableName"]) && !empty($_POST["idName"]) && !empty($_POST["idValue"])){
+            foreach ($_POST as $index => $value){
+                if(!in_array($index, ["action", "tableName", "idName", "idValue"])){
+                    $postData[$index] = $value;
+                }
+            }
+            $response = Objet::modifyObjectById($_POST["tableName"],
+                [
+                    "name" => $_POST["idName"],
+                    "value" => $_POST["idValue"]
+                ],
+                $postData);
+            if($response['status'] === "fail"){
+                $response['status'] = "danger";
+            }
+
+            return view('sql-result', [
+                'pageTitle' => "Modification d'un(e) {$_POST["tableName"]}",
+                'response' => $response
+            ]);
         }
-        return "";
+        return view('simple-data', [
+            'pageTitle' => "Erreur",
+            'pageContent' => "Il manque des paramètres dans l'url."
+        ]);
     }
 }
\ No newline at end of file
diff --git a/models/Objet.php b/models/Objet.php
index 1ed669f..4c2bd6a 100644
--- a/models/Objet.php
+++ b/models/Objet.php
@@ -105,9 +105,10 @@ class Objet
      * @param array $columns
      * @return array|string[]
      */
-    public static function modifyObject(String $tableName, array $id, array $columns) : array
+    public static function modifyObjectById(String $tableName, array $id, array $columns) : array
     {
         $result["status"] = "success";
+        $result["message"] = "Modification réussie";
 
         $validation = Objet::verifyTableAndFormat($tableName, $columns);
         if($validation["status"] !== "success"){
@@ -121,11 +122,16 @@ class Objet
         }
 
         // On prépare la requête
-        $queryString = ("UPDATE $tableName SET " . http_build_query($columns, '', ',') . " WHERE " . $id["name"] . "=:" . $id["name"]);
+        foreach ($columns as $index => $value){
+            $updateQuery[] = "$index=:$index";
+        }
+        $queryString = ("UPDATE $tableName SET " . implode(", ", $updateQuery) . " WHERE " . $id["name"] . "=:" . $id["name"]);
         $insertQuery = Database::pdo()->prepare($queryString);
         try{
             // Et on l'exécute
-            $insertQuery->execute($columns);
+            $insertQuery->execute(array_merge($columns, [
+                $id["name"] => $id["value"]
+            ]));
         } catch (PDOException $e) {
             return [
                 "status" => "fail",
diff --git a/resources/views/data-grid.php b/resources/views/data-grid.php
index ee77f58..7ba5a4b 100644
--- a/resources/views/data-grid.php
+++ b/resources/views/data-grid.php
@@ -19,7 +19,7 @@
                     Lire les détails
                 </a>
                 <a class="btn btn-outline-primary"
-                href="index.php?action=modifierObjet&tableName={{ $object['type'] }}&id_name={{ $object['id_name'] }}&id_value={{ $object['id_value'] }}">
+                href="index.php?action=modifierObjet&tableName={{ $object['type'] }}&idName={{ $object['idName'] }}&idValue={{ $object['idValue'] }}">
                     Modifier
                 </a>
             </div>
diff --git a/resources/views/formulaire-modification-objet.php b/resources/views/formulaire-modification-objet.php
new file mode 100644
index 0000000..0fe1c87
--- /dev/null
+++ b/resources/views/formulaire-modification-objet.php
@@ -0,0 +1,30 @@
+@extends('layouts.page-layout')
+
+@section('title', '{{ $pageTitle }}')
+
+@section('content')
+<div class="container mt-3">
+    <h1>{{ $pageTitle }}</h1>
+
+    <form action="index.php" method="post" class="mt-2 max-700" id="objectForm">
+        <input type="text" name="action" value="modifierObjet" hidden>
+        <input type="text" name="tableName" value="{{ $_GET['tableName'] }}" hidden>
+        <input type="text" name="idName" value="{{ $_GET['idName'] }}" hidden>
+        <input name="idValue" value="{{ $_GET['idValue'] }}" hidden>
+        @foreach($properties as $property)
+            <div class="form-group mb-3">
+                <label for="{{ $property['name'] }}">{{ $property['showName'] }}</label>
+                <input type="{{ $property['type'] }}"
+                       name="{{ $property['name'] }}"
+                       value="{{ $property['value'] }}"
+                       class="form-control">
+                @if($property['comment'] !== "")
+                    <small class="form-text text-muted">{{ $property['comment'] }}</small>
+                @endif
+            </div>
+        @endforeach
+        <button type="submit" class="btn btn-primary">Modifier</button>
+    </form>
+</div>
+</div>
+@endsection
\ No newline at end of file
diff --git a/resources/views/sql-result.php b/resources/views/sql-result.php
new file mode 100644
index 0000000..e8a6ea1
--- /dev/null
+++ b/resources/views/sql-result.php
@@ -0,0 +1,17 @@
+@extends('layouts.page-layout')
+
+@section('title', '{{ $pageTitle }}')
+
+@section('content')
+<div class="container mt-3">
+    <h1>{{ $pageTitle }}</h1>
+    <div class="alert alert-{{ $response["status"] }}" role="alert">
+        @if(!empty($response["pdoError"]))
+            <strong>{{ $response["message"] }}</strong>
+            <br>{{ $response["pdoError"]->getMessage() }}
+        @else
+            {{ $response["message"] }}
+        @endif
+    </div>
+</div>
+@endsection
\ No newline at end of file
-- 
GitLab