Skip to content
Snippets Groups Projects
Commit f12db57e authored by Sofiane Lasri's avatar Sofiane Lasri
Browse files

Fin de TP5 ex1.

parent 64983ddb
No related branches found
No related tags found
No related merge requests found
Showing
with 849 additions and 0 deletions
DB_HOST=localhost
DB_NAME=iut-dev
DB_LOGIN=iut-dev-user
DB_PASSWORD=p73i74KAV8lami2iyIpehE5ozic8GA
File added
<?php
/**
* @param string $index
* @return string
*/
function config(string $index) : string
{
$envPath = getcwd() . "/.env";
if(file_exists($envPath)){
$index = str_replace('_', '\\_', $index);
$envFile = file_get_contents($envPath);
preg_match("/" . $index . '=(.*?)\n/', $envFile, $matches);
$value = $matches[count($matches) - 1];
$value = preg_replace('/[^A-Za-z0-9\-]/', '', $value);
return $value;
} else {
return "";
}
}
\ No newline at end of file
<?php
require_once("app/models/View.php");
/**
* Charge le contenu d'une vue avec des paramètres.
* @param string $viewName
* @param array $args
* @return string
*/
function view(string $viewName, array $args = []): string
{
return View::load($viewName, $args);
}
\ No newline at end of file
<?php
class Database
{
// les attributs static caractéristiques de la connexion
static private $hostname = 'localhost';
static private $database = 'iut-dev';
static private $login = 'iut-dev-user';
static private $password = 'p73i74KAV8lami2iyIpehE5ozic8GA';
static private $tabUTF8 = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
// l'attribut static qui matérialisera la connexion
static private $pdo;
// le getter public de cet attribut
static public function pdo()
{
return self::$pdo;
}
// la fonction static de connexion qui initialise $pdo et lance la tentative de connexion
static public function connect()
{
$hostname = config("DB_HOST");
$database = config("DB_NAME");
$login = config("DB_LOGIN");
$password = config("DB_PASSWORD");
$t = self::$tabUTF8;
try {
self::$pdo = new PDO("mysql:host=$hostname;dbname=$database", $login, $password, $t);
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Erreur de connexion : " . $e->getMessage() . "<br>";
}
}
}
?>
<?php
/**
* Tentative de créer un système de template.
*/
class View
{
/**
* S'occupe d'ouvrir la template.
* @param string $viewName
* @param array $args
* @return string
*/
public static function load(string $viewName, array $args = []): string
{
$viewPathParts = explode(".", $viewName);
$viewPath = "";
foreach ($viewPathParts as $pathPart){
$viewPath .= "/" . $pathPart;
}
$viewPath = "resources/views" . $viewPath . ".php";
if(file_exists($viewPath)){
return self::render(self::parse($viewPath), $args);
}else{
return "La vue " . $viewName . " est introuvable.";
}
}
/**
* S'occuper de remplir la template
* @param string $viewPath
* @param array $args
* @return string
*/
public static function parse(string $viewPath): string
{
$viewContent = file_get_contents($viewPath);
// On va chercher le @extends('nom-de-la-vue') (seul le premier est pris en compte)
preg_match("/@extends[ ]{0,1}\([\"|'](.*?)[\"|']\)/", $viewContent, $extendMatch);
if(!empty($extendMatch)){
$contentToPlaceInExtends = str_replace($extendMatch[0], "", $viewContent);
$viewContent = self::load($extendMatch[1]);
// Maintenant on va regarder si on a pas des @yield('nom') à remplacer
// On commence avec les @section("nom", "valeur"). L'ordre est important car la second regex peut englober la première.
preg_match_all("/@section[ ]{0,1}\([ ]{0,1}[\"|'](.*?)[\"|'][ ]{0,1},[ ]{0,1}[\"|'](.*?)[\"|'][ ]{0,1}\)/",
$contentToPlaceInExtends, $inlineSectionMatches);
for($i = 0; $i<count($inlineSectionMatches[0]); $i++){
$viewContent = preg_replace(
"/@yield[ ]{0,1}\([\"|']" . preg_quote($inlineSectionMatches[1][$i]) . "[\"|']\)/",
$inlineSectionMatches[2][$i],
$viewContent
);
// On supprime la directive dans le contenu mis de côté car la regex du dessous capte aussi celle-ci.
$contentToPlaceInExtends = str_replace($inlineSectionMatches[0][$i],
$inlineSectionMatches[2][$i],
$contentToPlaceInExtends);
}
// Et @section("nom") --> @endsection
preg_match_all("/@section[ ]{0,1}\([ ]{0,1}[\"|'](.*?)[\"|'][ ]{0,1}\)((\n|.)*?)@endsection/",
$contentToPlaceInExtends, $sectionMatches);
for($i = 0; $i<count($sectionMatches[0]); $i++){
//echo $sectionMatches[1][$i] . " - " . $sectionMatches[2][$i];
$viewContent = preg_replace(
"/@yield[ ]{0,1}\([\"|']" . preg_quote($sectionMatches[1][$i]) . "[\"|']\)/",
$sectionMatches[2][$i],
$viewContent
);
}
}
// On va rechercher toutes les concaténations {{ $var }}
$viewContent = preg_replace("/\{\{(.*?)\}\}/", "<?=$1?>", $viewContent);
// On va rechercher tous les @foreach($var1 as $var2) @endforeach
$viewContent = preg_replace("/@foreach[ ]{0,1}\((.*?) as (.*?)\)/",
"<?php foreach($1 as $2) { ?>", $viewContent);
$viewContent = preg_replace("/@endforeach/", "<?php } ?>", $viewContent);
return $viewContent;
}
/**
* @param string $viewCode
* @param array $args
* @return string
*/
public static function render(string $viewCode, array $args = []): string
{
extract($args);
// On ouvre le buffer pour enregistrer le résultat de l'echo.
ob_start();
eval("?>" . $viewCode . "<?php");
return ob_get_clean();
}
}
\ No newline at end of file
<?php
require_once "ControleurObjet.php";
require_once("models/Adherent.php");
class ControleurAdherent extends ControleurObjet
{
/**
* Charge la page de la liste des adhérents.
* @return string
* @throws Exception
*/
public static function lireAdherents(): string
{
$adherents = Adherent::getAllAdherents();
$objects = [];
foreach ($adherents as $adherent){
$object['title'] = $adherent->prenomAdherent . " " . $adherent->nomAdherent;
$object['desc'] = "ID: {$adherent->login}<br>Date d'adhésion: {$adherent->dateAdhesion->format("Y-m-d")}";
$object['url'] = "index.php?action=lireAdherent&login={$adherent->login}";
$objects[] = $object;
}
return view('data-grid', [
'pageTitle' => 'Liste des adhérents',
'pageDesc' => 'Voici la liste de tous les adhérents',
'objects' => $objects
]);
}
/**
* Charge la page du détail d'un adhérent.
* @return string
* @throws Exception
*/
public static function lireAdherent(): string
{
if (empty($_GET["login"])) {
die("Le paramètre login n'est pas spécifié.");
}
$adherent = Adherent::getAdherentByLogin($_GET["login"]);
return view('simple-data', [
'pageTitle' => 'Information du libre',
'pageContent' => $adherent->afficher()
]);
}
}
\ No newline at end of file
<?php
require_once "ControleurObjet.php";
require_once("models/Auteur.php");
class ControleurAuteur extends ControleurObjet
{
/**
* Charge la page de la liste des auteurs.
* @return string
*/
public static function lireAuteurs() : string
{
$auteurs = Auteur::getAllAuteurs();
$objects = [];
foreach ($auteurs as $auteur){
$object['title'] = $auteur->prenom . " " . $auteur->nom;
$object['desc'] = "ID: {$auteur->numAuteur}<br>Date de naissance: {$auteur->anneeNaissance}";
$object['url'] = "index.php?action=lireAuteur&numAuteur={$auteur->numAuteur}";
$objects[] = $object;
}
return view('data-grid', [
'pageTitle' => 'Liste des auteurs',
'pageDesc' => 'Voici la liste de tous les auteurs',
'objects' => $objects
]);
}
/**
* Charge la page du détail d'un auteur.
* @return string
*/
public static function lireAuteur() : string
{
if (empty($_GET["numAuteur"])) {
die("Le paramètre numAuteur n'est pas spécifié.");
}
$auteur = Auteur::getAuteurByNum($_GET["numAuteur"]);
return view('simple-data', [
'pageTitle' => 'Information du libre',
'pageContent' => $auteur->afficher()
]);
}
}
?>
<?php
require_once "ControleurObjet.php";
require_once("models/Livre.php");
class ControleurLivre extends ControleurObjet
{
/**
* Charge la page de la liste des adhérents.
* @return string
* @throws Exception
*/
public static function lireLivres(): string
{
$livres = Livre::getAllLivres();
$objects = [];
foreach ($livres as $livre){
$object['title'] = $livre->titre;
$object['desc'] = "ID: {$livre->numLivre}<br>Année de parution: {$livre->anneeParution}";
$object['url'] = "index.php?action=lireLivre&numLivre={$livre->numLivre}";
$objects[] = $object;
}
return view('data-grid', [
'pageTitle' => 'Liste des livres',
'pageDesc' => 'Voici la liste de tous les livres',
'objects' => $objects
]);
}
/**
* Charge la page du détail d'un adhérent.
* @return string
* @throws Exception
*/
public static function lireLivre(): string
{
if (empty($_GET["numLivre"])) {
die("Le paramètre numLivre n'est pas spécifié.");
}
$livre = Livre::getLivreByNumLivre($_GET["numLivre"]);
return view('simple-data', [
'pageTitle' => 'Information du libre',
'pageContent' => $livre->afficher()
]);
}
}
\ No newline at end of file
<?php
class ControleurObjet
{
}
\ No newline at end of file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("app/helpers/config.php");
require_once("app/helpers/views.php");
require_once("app/models/Database.php");
require_once("controller/ControleurAuteur.php");
require_once("controller/ControleurAdherent.php");
require_once("controller/ControleurLivre.php");
Database::connect();
if (empty($_GET["action"])) {
echo ControleurAuteur::lireAuteurs();
} else {
if (in_array($_GET["action"], get_class_methods('ControleurAuteur'))) {
$action = $_GET["action"];
echo ControleurAuteur::$action();
} elseif (in_array($_GET["action"], get_class_methods('ControleurAdherent'))) {
$action = $_GET["action"];
echo ControleurAdherent::$action();
} elseif (in_array($_GET["action"], get_class_methods('ControleurLivre'))) {
$action = $_GET["action"];
echo ControleurLivre::$action();
}
}
?>
<?php
require_once "Objet.php";
class Adherent extends Objet
{
protected string $login;
protected string $mdp;
protected string $nomAdherent;
protected string $prenomAdherent;
protected string $email;
protected DateTime $dateAdhesion;
protected int $numCategorie;
/**
* @param string $login
* @param string $mdp
* @param string $nomAdherent
* @param string $prenomAdherent
* @param string $email
* @param DateTime $dateAdhesion
* @param int $numCategorie
*/
public function __construct(string $login, string $mdp, string $nomAdherent, string $prenomAdherent, string $email, DateTime $dateAdhesion, int $numCategorie)
{
$this->login = $login;
$this->mdp = $mdp;
$this->nomAdherent = $nomAdherent;
$this->prenomAdherent = $prenomAdherent;
$this->email = $email;
$this->dateAdhesion = $dateAdhesion;
$this->numCategorie = $numCategorie;
}
/**
* @return array
* @throws Exception
*/
public static function getAllAdherents(): array
{
// écriture de la requête
$requete = "SELECT * FROM Adherent;";
// envoi de la requête et stockage de la réponse
$resultat = Database::pdo()->query($requete);
// traitement de la réponse
$resultat->setFetchmode(PDO::FETCH_ASSOC);
$resultat = $resultat->fetchAll();
$tableau = array();
foreach ($resultat as $row){
$tableau[] = new Adherent($row['login'],
$row['mdp'],
$row['nomAdherent'],
$row['prenomAdherent'],
$row['email'],
new DateTime($row['dateAdhesion']),
$row['numCategorie']);
}
return $tableau;
}
/**
* Trouve un adhérent selon son login unique.
* @param $login
* @return Adherent
* @throws Exception
*/
public static function getAdherentByLogin($login) : Adherent
{
// écriture de la requête
$requetePreparee = "SELECT * FROM Adherent WHERE login = :login;";
$req_prep = Database::pdo()->prepare($requetePreparee);
// le tableau des valeurs
$valeurs = array("login" => $login);
$response = null;
try {
// envoi de la requête
$req_prep->execute($valeurs);
// traitement de la réponse
$req_prep->setFetchmode(PDO::FETCH_ASSOC);
// récupération de l'auteur
$row = $req_prep->fetch();
$response = new Adherent($row['login'],
$row['mdp'],
$row['nomAdherent'],
$row['prenomAdherent'],
$row['email'],
new DateTime($row['dateAdhesion']),
$row['numCategorie']);
} catch (PDOException $e) {
echo $e->getMessage();
}
return $response;
}
/**
* @return string
*/
public function afficher(): string
{
return "<p>" . $this->prenomAdherent . " " . $this->nomAdherent . " a rejoint le "
.$this->dateAdhesion->format('Y-m-d H:i:s');
}
}
\ No newline at end of file
<?php
require_once "Objet.php";
class Auteur extends Objet
{
// attributs
protected ?int $numAuteur;
protected ?string $nom;
protected ?string $prenom;
protected ?int $anneeNaissance;
// getter
public function __construct($nu = NULL, $n = NULL, $p = NULL, $a = NULL)
{
if (!is_null($nu)) {
$this->numAuteur = $nu;
$this->nom = $n;
$this->prenom = $p;
$this->anneeNaissance = $a;
}
}
public static function getAllAuteurs()
{
// écriture de la requête
$requete = "SELECT * FROM Auteur;";
// envoi de la requête et stockage de la réponse
$resultat = Database::pdo()->query($requete);
// traitement de la réponse
$resultat->setFetchmode(PDO::FETCH_CLASS, 'Auteur');
$tableau = $resultat->fetchAll();
return $tableau;
}
public static function getAuteurByNum($numAuteur)
{
// écriture de la requête
$requetePreparee = "SELECT * FROM Auteur WHERE numAuteur = :num_tag;";
$req_prep = Database::pdo()->prepare($requetePreparee);
// le tableau des valeurs
$valeurs = array("num_tag" => $numAuteur);
$response = null;
try {
// envoi de la requête
$req_prep->execute($valeurs);
// traitement de la réponse
$req_prep->setFetchmode(PDO::FETCH_CLASS, 'Auteur');
// récupération de l'auteur
$response = $req_prep->fetch();
// retour
} catch (PDOException $e) {
echo $e->getMessage();
}
return $response;
}
// méthode static qui retourne un auteur identifié par son numAuteur
public function afficher()
{
return "<p>auteur $this->prenom $this->nom, né(e) en $this->anneeNaissance </p>";
}
}
?>
<?php
/**
*
*/
class Categorie
{
private int $numCategorie;
private string $libelle;
private int $nbLivresAutorises;
/**
* @param int $numCategorie
* @param string $libelle
* @param int $nbLivresAutorises
*/
public function __construct(int $numCategorie, string $libelle, int $nbLivresAutorises)
{
$this->numCategorie = $numCategorie;
$this->libelle = $libelle;
$this->nbLivresAutorises = $nbLivresAutorises;
}
/**
* @return int
*/
public function getNumCategorie(): int
{
return $this->numCategorie;
}
/**
* @param int $numCategorie
*/
public function setNumCategorie(int $numCategorie): void
{
$this->numCategorie = $numCategorie;
}
/**
* @return string
*/
public function getLibelle(): string
{
return $this->libelle;
}
/**
* @param string $libelle
*/
public function setLibelle(string $libelle): void
{
$this->libelle = $libelle;
}
/**
* @return int
*/
public function getNbLivresAutorises(): int
{
return $this->nbLivresAutorises;
}
/**
* @param int $nbLivresAutorises
*/
public function setNbLivresAutorises(int $nbLivresAutorises): void
{
$this->nbLivresAutorises = $nbLivresAutorises;
}
/**
* @return void
*/
public function afficher(): void{
echo "<p>Le livre" . $this->libelle . " est autorisé " . $this->nbLivresAutorises . " fois.</p>";
}
}
\ No newline at end of file
<?php
class DateEmprunt
{
private int $numDateEmprunt;
private DateTime $dateEmrpunt;
/**
* @return int
*/
public function getNumDateEmprunt(): int
{
return $this->numDateEmprunt;
}
/**
* @param int $numDateEmprunt
*/
public function setNumDateEmprunt(int $numDateEmprunt): void
{
$this->numDateEmprunt = $numDateEmprunt;
}
/**
* @return DateTime
*/
public function getDateEmrpunt(): DateTime
{
return $this->dateEmrpunt;
}
/**
* @param DateTime $dateEmrpunt
*/
public function setDateEmrpunt(DateTime $dateEmrpunt): void
{
$this->dateEmrpunt = $dateEmrpunt;
}
}
\ No newline at end of file
<?php
class Genre
{
private int $numGenre;
private string $intitule;
/**
* @param int $numGenre
* @param string $intitule
*/
public function __construct(int $numGenre, string $intitule)
{
$this->numGenre = $numGenre;
$this->intitule = $intitule;
}
/**
* @return int
*/
public function getNumGenre(): int
{
return $this->numGenre;
}
/**
* @param int $numGenre
*/
public function setNumGenre(int $numGenre): void
{
$this->numGenre = $numGenre;
}
/**
* @return string
*/
public function getIntitule(): string
{
return $this->intitule;
}
/**
* @param string $intitule
*/
public function setIntitule(string $intitule): void
{
$this->intitule = $intitule;
}
}
\ No newline at end of file
<?php
require_once "Objet.php";
class Livre extends Objet
{
protected int $numLivre;
protected string $titre;
protected int $anneeParution;
protected int $numGenre;
/**
* @param int $numLivre
* @param string $titre
* @param int $anneeParution
* @param int $numGenre
*/
public function __construct(int $numLivre, string $titre, int $anneeParution, int $numGenre)
{
$this->numLivre = $numLivre;
$this->titre = $titre;
$this->anneeParution = $anneeParution;
$this->numGenre = $numGenre;
}
/**
* @return array
*/
public static function getAllLivres(): array
{
$query = Database::pdo()->query("SELECT * FROM Livre");
$query->setFetchmode(PDO::FETCH_ASSOC);
$queryResult = $query->fetchAll();
$tableau = array();
foreach ($queryResult as $row) {
$tableau[] = new Livre($row['numLivre'],
$row['titre'],
$row['anneeParution'],
$row['numGenre']);
}
return $tableau;
}
/**
* @param int $numLivre
* @return Livre
*/
public static function getLivreByNumLivre(int $numLivre): Livre
{
$query = Database::pdo()->prepare("SELECT * FROM Livre WHERE numLivre = :numLivre");
$response = null;
try {
// envoi de la requête
$query->execute(['numLivre' => $numLivre]);
$query->setFetchmode(PDO::FETCH_ASSOC);
$queryResult = $query->fetch();
$response = new Livre($queryResult['numLivre'],
$queryResult['titre'],
$queryResult['anneeParution'],
$queryResult['numGenre']);
} catch (PDOException $e) {
echo $e->getMessage();
}
return $response;
}
/**
* @return string
*/
public function afficher(): string
{
return "<p>" . $this->titre . " est paru en "
. $this->anneeParution;
}
}
\ No newline at end of file
<?php
class Nationalite
{
private int $numNationalite;
private string $pays;
private string $abrege;
/**
* @param int $numNationalite
* @param string $pays
* @param string $abrege
*/
public function __construct(int $numNationalite, string $pays, string $abrege)
{
$this->numNationalite = $numNationalite;
$this->pays = $pays;
$this->abrege = $abrege;
}
/**
* @return int
*/
public function getNumNationalite(): int
{
return $this->numNationalite;
}
/**
* @param int $numNationalite
*/
public function setNumNationalite(int $numNationalite): void
{
$this->numNationalite = $numNationalite;
}
}
\ No newline at end of file
<?php
require_once "Objet.php";
/**
* Implémente les magic methods.
*/
class Objet
{
public function __construct($data = null)
{
if(!is_null($data)){
foreach ($data as $key => $value){
$this->$key = $value;
}
}
}
/**
* @param $name
* @return mixed
*/
public function __get($name)
{
return $this->$name ?? null;
}
/**
* @param $name
* @param $value
* @return void
*/
public function __set($name, $value)
{
$this->$name = $value;
}
}
\ No newline at end of file
.ligne {
display:flex;
flex-direction: row;
justify-content: space-between;
margin-top:10px;
margin-left:5%;
width:50%;
}
nav {
margin:10px;
padding:5px;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment