Last active
December 23, 2016 15:19
-
-
Save SebDeclercq/18ccfbab9e33c1a83b81f4ca961fc259 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Json implements RessourceRestPersonne | |
| { | |
| static public function getPersonnes() { | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $pdostmt = $pdo->prepare('SELECT * FROM rest;'); | |
| $pdostmt->execute(); | |
| $personnes = $pdostmt->fetchAll(PDO::FETCH_OBJ); | |
| $pdo = null; | |
| return json_encode($personnes); | |
| } | |
| static public function getPersonneParId($id) { | |
| if (isset($id) && preg_match('/^\d+$/', $id)) { | |
| $id = (int)$id; | |
| } | |
| else { | |
| $msg = 'Mauvais argument id : /personne/{id} (id = integer)'; | |
| return genereMessageAvecCode($msg); | |
| } | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $pdostmt = $pdo->prepare("SELECT * FROM rest WHERE id = $id;"); | |
| $pdostmt->execute(); | |
| $personne = $pdostmt->fetch(PDO::FETCH_OBJ); | |
| $pdo = null; | |
| if (isset($personne->id)) { | |
| return json_encode($personne); | |
| } | |
| else { | |
| $msg = 'Personne inconnue'; | |
| return self::genereMessageAvecCode($msg, 404); | |
| } | |
| } | |
| static public function postPersonne() { | |
| $personne = json_decode(file_get_contents('php://input')); | |
| if (!isset($personne->nom) || !isset($personne->anneeDeNaissance)) { | |
| $msg = "Une personne doit avoir un {nom} et une {anneeDeNaissance}"; | |
| return self::genereMessageAvecCode($msg); | |
| } | |
| else { | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $sql = "INSERT INTO rest (nom, anneeDeNaissance) VALUES ('$personne->nom', $personne->anneeDeNaissance);"; | |
| if ($pdo->exec($sql) == 1) { | |
| return self::getPersonneParId($pdo->lastInsertId()); | |
| } | |
| else { | |
| $msg = "Une erreur est survenue lors de l'insertion"; | |
| return self::genereMessageAvecCode($msg); | |
| } | |
| } | |
| } | |
| static public function genereMessageAvecCode($message, $code=400) { | |
| header(' ', true, $code); | |
| $sortie = new stdClass; | |
| $sortie->datetime = date('Y-m-d G:i:s'); | |
| $sortie->code = $code; | |
| $sortie->message = $message; | |
| return json_encode($sortie); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
| $pdo->exec('DROP TABLE IF EXISTS rest;'); | |
| $pdo->exec('CREATE TABLE rest (id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, nom VARCHAR(15), anneeDeNaissance INT);'); | |
| for ($i=0;$i<100;$i++) { | |
| $nom = random(range('A', 'Z')); | |
| $max = rand(0, 15); | |
| for ($j=0;$j<$max;$j++) { | |
| $nom .= random(range('a', 'z')); | |
| } | |
| $anneeDeNaissance = rand(1900, 2016); | |
| $pdo->exec("INSERT INTO rest (nom, anneeDeNaissance) VALUES ('$nom', $anneeDeNaissance);"); | |
| } | |
| $pdo = null; | |
| function random(array $array) { | |
| shuffle($array); | |
| return array_shift($array); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| interface RessourceRestPersonne | |
| { | |
| static public function getPersonnes(); | |
| static public function getPersonneParId($id); | |
| static public function postPersonne(); | |
| static public function genereMessageAvecCode($message, $code=400); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| require_once('RessourceRestPersonne.interface.php'); | |
| require_once('Xml.classe.php'); | |
| require_once('Json.classe.php'); | |
| $formatsSupportes = array('application/json', 'application/xml'); // Formats supportés par l'appli | |
| $formatAutorise = parseAcceptHeader(); // Appelle à la fonction de Lorna Jane | |
| foreach ($formatAutorise as $formatSortie) { // Comme l'array est trié par préférence, le 1er match sera le bon format | |
| if (in_array($formatSortie, $formatsSupportes)) { | |
| break; | |
| } | |
| else { // Par défaut | |
| $formatSortie = 'application/json'; | |
| } | |
| } | |
| if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != '/') { | |
| $params = explode('/', substr($_SERVER['PATH_INFO'], 1)); // Génère un array avec les params, en enlevant la racine | |
| } | |
| else { | |
| $msg = "Veuillez préciser l'opération à réaliser"; | |
| switch ($formatSortie) { | |
| case 'application/xml' : { | |
| echo Xml::genereMessageAvecCode($msg); | |
| break; | |
| } | |
| case 'application/json' : | |
| default : { | |
| echo Json::genereMessageAvecCode($msg); | |
| break; | |
| } | |
| } | |
| exit(); | |
| } | |
| $options = $_GET; // Récupère les options | |
| if (in_array('reset', array_keys($options))) { | |
| include('populeBdd.php'); // Lance populeBdd.php | |
| } | |
| switch ($_SERVER['REQUEST_METHOD']) { | |
| case 'GET' : { | |
| switch ($formatSortie) { | |
| case 'application/xml' : { | |
| if ($params[0] == 'personnes') { | |
| $retour = Xml::getPersonnes(); | |
| } | |
| elseif ($params[0] == 'personne') { | |
| $retour = Xml::getPersonneParId($params[1]); | |
| } | |
| else { | |
| $msg = 'Requête non comprise'; | |
| $retour = Xml::genereMessageAvecCode($msg); | |
| } | |
| header('Content-type: application/xml'); | |
| break; | |
| } | |
| case 'application/json' : // break volontairement omis | |
| default : { // Défaut = JSON | |
| if ($params[0] == 'personnes') { | |
| $retour = Json::getPersonnes(); | |
| } | |
| elseif ($params[0] == 'personne') { | |
| $retour = Json::getPersonneParId($params[1]); | |
| } | |
| else { | |
| $msg = 'Requête non comprise'; | |
| $retour = Json::genereMessageAvecCode($msg); | |
| } | |
| header('Content-type: application/json'); | |
| break; | |
| } | |
| } | |
| echo $retour; | |
| break; | |
| } | |
| case 'PUT' : // break volontairement omis | |
| case 'POST' : { | |
| $formatEntree = $_SERVER['CONTENT_TYPE']; | |
| switch ($formatEntree) { | |
| case 'application/xml' : { | |
| $retour = Xml::postPersonne(); | |
| header('Content-type: application/xml'); | |
| break; | |
| } | |
| case 'application/json' : { | |
| $retour = Json::postPersonne(); | |
| header('Content-type: application/json'); | |
| break; | |
| } | |
| default : { | |
| $msg = 'Format non-supporté. Veuillez fournir du Json ou du Xml'; | |
| $retour = Json::genereMessageAvecCode($msg, 415); // Unsupported Media Type | |
| header('Content-type: application/json'); | |
| break; | |
| } | |
| } | |
| echo $retour; | |
| break; | |
| } | |
| case 'DELETE' : { | |
| if ($params[0] == 'personne' && isset($params[1]) && preg_match('/^\d+$/', $params[1])) { | |
| $id = (int)$params[1]; | |
| $retour = deleteEnBdd($id); | |
| if ($retour === true) { | |
| $msg = "La suppression s'est déroulée avec succès"; | |
| $code = 200; | |
| } | |
| else { | |
| $msg = "Une erreur est survenue lors de la suppression"; | |
| $code = 417; // Expectation failed | |
| } | |
| switch ($formatSortie) { | |
| case 'application/xml' : { | |
| $retour = Xml::genereMessageAvecCode($msg, $code); | |
| break; | |
| } | |
| case 'application/json' : | |
| default : { | |
| $retour = Json::genereMessageAvecCode($msg, $code); | |
| break; | |
| } | |
| } | |
| echo $retour; | |
| break; | |
| } | |
| } | |
| default : { | |
| $msg = "Verbe HTTP $_SERVER[REQUEST_METHOD] inconnu"; | |
| switch ($formatSortie) { | |
| case 'application/xml' : { | |
| $retour = Xml::genereMessageAvecCode($msg); | |
| break; | |
| } | |
| case 'application/json' : | |
| default : { | |
| $retour = Json::genereMessageAvecCode($msg); | |
| break; | |
| } | |
| } | |
| echo $retour; | |
| } | |
| } | |
| function deleteEnBdd($id) { | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $sql = "DELETE FROM rest WHERE id = $id;"; | |
| if ($pdo->exec($sql) == 1) { | |
| return true; | |
| } | |
| else { | |
| return false; | |
| } | |
| $pdo = null; | |
| } | |
| /* Lorna Jane : PHP WebServices (voir github) */ | |
| function parseAcceptHeader() { | |
| $hdr = $_SERVER['HTTP_ACCEPT']; | |
| $accept = array(); | |
| foreach (preg_split('/\s*,\s*/', $hdr) as $i => $term) { | |
| $o = new \stdclass; | |
| $o->pos = $i; | |
| if (preg_match(",^(\S+)\s*;\s*(?:q|level)=([0-9\.]+),i", $term, $M)) { | |
| $o->type = $M[1]; | |
| $o->q = (double)$M[2]; | |
| } else { | |
| $o->type = $term; | |
| $o->q = 1; | |
| } | |
| $accept[] = $o; | |
| } | |
| usort($accept, function ($a, $b) { | |
| /* first tier: highest q factor wins */ | |
| $diff = $b->q - $a->q; | |
| if ($diff > 0) { | |
| $diff = 1; | |
| } else if ($diff < 0) { | |
| $diff = -1; | |
| } else { | |
| /* tie-breaker: first listed item wins */ | |
| $diff = $a->pos - $b->pos; | |
| } | |
| return $diff; | |
| }); | |
| $accept_data = array(); | |
| foreach ($accept as $a) { | |
| $accept_data[] = $a->type; | |
| } | |
| return $accept_data; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Xml implements RessourceRestPersonne | |
| { | |
| static public function getPersonnes() { | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $personnes = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><personnes/>'); | |
| $personnes->addAttribute("date", date('Ymd')); | |
| $pdostmt = $pdo->prepare('SELECT * FROM rest;'); | |
| $pdostmt->execute(); | |
| foreach ($pdostmt->fetchAll(PDO::FETCH_OBJ) as $enr) { | |
| $personne = $personnes->addChild('personne'); | |
| $personne->addAttribute('id', $enr->id); | |
| $personne->addChild('nom', $enr->nom); | |
| $personne->addChild('anneeDeNaissance', $enr->anneeDeNaissance); | |
| } | |
| $pdo = null; | |
| $dom = dom_import_simplexml($personnes)->ownerDocument; | |
| $dom->formatOutput = true; | |
| return $dom->saveXML(); | |
| } | |
| static public function getPersonneParId($id) { | |
| if (isset($id) && preg_match('/^\d+$/',$id)) { | |
| $id = (int)$id; | |
| } | |
| else { | |
| $msg = 'Mauvais argument id : /personne/{id} (id = integer)'; | |
| return genereMessageAvecCode($msg); | |
| } | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $pdostmt = $pdo->prepare("SELECT * FROM rest WHERE id = $id;"); | |
| $pdostmt->execute(); | |
| $enr = $pdostmt->fetch(PDO::FETCH_OBJ); | |
| $pdo = null; | |
| if (isset($enr->id)) { | |
| $personne = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><personne/>'); | |
| $personne->addAttribute('id', $enr->id); | |
| $personne->addChild('nom', $enr->nom); | |
| $personne->addChild('anneeDeNaissance', $enr->anneeDeNaissance); | |
| } | |
| else { | |
| $msg = 'Personne inconnue'; | |
| return self::genereMessageAvecCode($msg, 404); | |
| } | |
| $dom = dom_import_simplexml($personne)->ownerDocument; | |
| $dom->formatOutput = true; | |
| return $dom->saveXML(); | |
| } | |
| static public function postPersonne() { | |
| $xml = file_get_contents('php://input'); | |
| $personne = new SimpleXMLElement($xml); | |
| if (!isset($personne->nom) || !isset($personne->anneeDeNaissance)) { | |
| $msg = "Une personne doit avoir un {nom} et une {anneeDeNaissance}"; | |
| return self::genereMessageAvecCode($msg); | |
| } | |
| else { | |
| $pdo = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'root', ''); | |
| $sql = "INSERT INTO rest (nom, anneeDeNaissance) VALUES ('$personne->nom', $personne->anneeDeNaissance);"; | |
| if ($pdo->exec($sql) == 1) { | |
| return self::getPersonneParId($pdo->lastInsertId()); | |
| } | |
| else { | |
| $msg = "Une erreur est survenue lors de l'insertion"; | |
| return self::genereMessageAvecCode($msg); | |
| } | |
| } | |
| } | |
| static public function genereMessageAvecCode($message, $code=400) { | |
| header(' ', true, $code); | |
| $erreur = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><message/>'); | |
| $erreur->addAttribute('datetime', date('Y-m-d G:i:s')); | |
| $erreur->addChild('code', $code); | |
| $erreur->addChild('message', $message); | |
| return $erreur->asXML(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment