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

Reformatage du code et préparation au TP 7.

parent f9c23a7d
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 553 deletions
File deleted
DB_HOST=localhost
DB_NAME=iut-dev
DB_LOGIN=iut-dev-user
DB_PASSWORD=p73i74KAV8lami2iyIpehE5ozic8GA
<?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
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("models/Adherent.php");
class ControleurAdherent
{
/**
* 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 livre',
'pageContent' => $adherent->afficher()
]);
}
}
\ No newline at end of file
<?php
require_once("models/Auteur.php");
/**
*
*/
class ControleurAuteur
{
/**
* 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 livre',
'pageContent' => $auteur->afficher()
]);
}
}
?>
<?php
require_once("models/Livre.php");
class ControleurLivre
{
/**
* 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 livre',
'pageContent' => $livre->afficher()
]);
}
}
\ 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 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
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;
}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="?action=lireAuteurs">Bibliothèque</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="?action=lireAuteurs">
Liste des auteurs
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="?action=lireAdherents">Liste des adéherents</a>
</li>
<li class="nav-item">
<a class="nav-link" href="?action=lireLivres">Liste des livres</a>
</li>
</ul>
</div>
</div>
</nav>
<script type="text/javascript">
const urlParams = new URLSearchParams(window.location.search);
let links = document.querySelectorAll('a[href="?action='+urlParams.get("action")+'"]');
for (var i=0; i<links.length; i++){
links[i].classList.add("active");
}
</script>
\ No newline at end of file
@extends('layouts.page-layout')
@section('title', '{{ $pageTitle }}')
@section('content')
<div class="container">
<h1>{{ $pageTitle }}</h1>
<p>{{ $pageDesc }}</p>
<div class="d-flex flex-wrap justify-content-between">
@foreach($objects as $object)
<div class="card mb-2" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{ $object['title'] }}</h5>
<p class="card-text">
{{ $object['desc'] }}
</p>
<a class="btn btn-primary"
href="{{ $object['url'] }}">
Lire les détails
</a>
</div>
</div>
@endforeach
</div>
</div>
@endsection
\ No newline at end of file
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield("title")</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body class="">
<?=view("components.navbar")?>
@yield("content")
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
@extends('layouts.page-layout')
@section('title', '{{ $pageTitle }}')
@section('content')
<div class="container">
<h1>{{ $pageTitle }}</h1>
{{ $pageContent }}
</div>
@endsection
\ No newline at end of file
<?php
$test = "TESTEUU";
echo('Ceci est un <?=$test?>!');
\ No newline at end of file
DB_HOST=localhost
DB_NAME=iut-dev
DB_LOGIN=iut-dev-user
DB_PASSWORD=p73i74KAV8lami2iyIpehE5ozic8GA
File deleted
<?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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment