feat: frontController et controller (fonctionnel pas fini)
continuous-integration/drone/push Build is passing Details

tests
Jeremy DUCOURTHIAL 2 years ago
parent a32105946b
commit 62d5109583

@ -0,0 +1,3 @@
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

@ -0,0 +1,43 @@
<?php
class ControllerAccueil
{
function __construct()
{
global $dsn, $user, $pass, $vues;
session_start();
try {
/*
$action = "";
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
*/
require($vues["accueil"]);
/*
switch ($action) {
case "goToSolo":
require($vues['Solo']);
break;
case "goToMulti":
require($vues['Multi']);
break;
case "goToAdmin":
break;
default:
require($vues["Accueil"]);
break;
}
*/
} catch (PDOException $e) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require(__DIR__.'/../vues/erreur.php');
} catch (Exception $e2) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require ($rep.$vues['erreur']);
}
}
}

@ -0,0 +1,42 @@
<?php
class ControllerMulti
{
function __construct()
{
global $dsn, $user, $pass, $vues;
session_start();
try {
require($vues["multi"]);
/*
$action = "";
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
switch ($action) {
case "goToLobby":
//require($vues['Solo']);
break;
case "CreateLobby":
//require($vues['Multi']);
break;
case "goToAcceuil":
require($vues['Accueil']);
break;
default:
require($vues['Multi']);
break;
}
*/
} catch (PDOException $e) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require(__DIR__.'/../vues/erreur.php');
} catch (Exception $e2) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require ($rep.$vues['erreur']);
}
}
}

@ -0,0 +1,41 @@
<?php
class ControllerSolo
{
function __construct()
{
global $dsn, $user, $pass, $vues;
session_start();
try {
require($vues['multi']);
/*
$action = "";
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
switch ($action) {
case "goToLobby":
//require($vues['Solo']);
break;
case "CreateLobby":
//require($vues['Multi']);
break;
case "goToAcceuil":
require($vues['Accueil']);
break;
default:
break;
}
*/
} catch (PDOException $e) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require(__DIR__.'/../vues/erreur.php');
} catch (Exception $e2) {
// $dataVueEreur[] = "Erreur inattendue!!! ";
// require ($rep.$vues['erreur']);
}
}
}

@ -1,28 +1,89 @@
<?php
class FrontController
//require 'usages/AltoRouter.php';
/*class FrontController
{
function __construct()
{
global $dsn, $user, $pass, $vues;
$listeAction_Administrator = array('goToAdministratorConnexion', 'verifValidation', 'ajoutSource', 'supprimerSource', 'setNbArticlesParPage', 'goToAdministratoristration', 'refreshData', 'quitterAdministrator');
$listeAction_Acceuil = array('goToSolo', 'goToMulti', 'goToAdmin');
try {
$action = "";
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
if (in_array($action, $listeAction_Administrator)) {
if ($Administrator == NULL) {
new ControllerAdministrator();
} else {
header("Location:" . $vues["AdministratorConnexion"]);
}
} else {
$gate = new GatewayAdministrator(new ConnectionBaseDeDonnee($dsn, $user, $pass));
if (in_array($action, $listeAction_Acceuil)) {
}
} catch (Exception $e) {
header("Location:" . $vues["erreur"]);
}
}
}*/
class FrontController
{
function __construct()
{
global $dsn, $user, $pass, $vues;
$listeAction_Acceuil = array('goToSolo', 'goToMulti', 'goToAdmin');
try {
$action = "";
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
// Initialize AltoRouter
$router = new AltoRouter();
//$router->setBasePath('/');
// Define routes
$router->map('GET', '/', 'ControllerAccueil'); // Route pour la page d'accueil
$router->map('GET', '/solo', 'ControllerSolo');
$router->map('GET', '/multi', 'ControllerMulti');
$router->map('GET', '/goToAdmin', 'ControllerAdmin');
// Match the current request
$match = $router->match();
var_dump($match);
if (!$match) {
echo "404"; // Redirige vers une page d'erreur 404
die;
}
if ($match) {
$controller = $match['target'];
$action=$match['params']['action'];
$id=$match['params']['id']; // paramètre 2
$controller = new $controller;
if (is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
}
/*
if (is_callable(array($controller, $action))) {
call_user_func_array(array($controller, $action), array($match['params'])); }
}
else {
if (is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
}
}
*/
}
}
catch (Exception $e) {
header("Location:" . $vues["erreur"]);
}
}
}

@ -8,12 +8,10 @@ class GatewayAdministrator
{
$this->con = $con;
}
/* private int $id;
private string $username;
private string $hashedPassword;*/
public function addAdministrator($administrator)
{
$query = "insert into Administrator(id,username,hashedPassword) values (:id,:username,:hashedPassword);";
$query = "insert into Administrators(id,username,hashedPassword) values (:id,:username,:hashedPassword);";
$this->con->executeQuery(
$query,
array(
@ -26,7 +24,7 @@ class GatewayAdministrator
public function getAdministratorByUsername(string $username)
{
$query = "SELECT * FROM Administrator WHERE username = :username;";
$query = "SELECT * FROM Administrators WHERE username = :username;";
$this->con->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -37,7 +35,7 @@ class GatewayAdministrator
public function getAdministratorByID(int $id)
{
$query = "SELECT * FROM Administrator WHERE id = :id;";
$query = "SELECT * FROM Administrators WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -48,7 +46,7 @@ class GatewayAdministrator
public function getAdministrators()
{
$query = "SELECT * FROM Administrator;";
$query = "SELECT * FROM Administrators;";
$this->con->executeQuery($query);
$results = $this->con->getResults();
if ($results == NULL) {
@ -58,7 +56,7 @@ class GatewayAdministrator
public function updateAdministrator($administrator)
{
$query = "UPDATE Administrator SET username = :username, hashedPassword = :hashedPassword WHERE id = :id;";
$query = "UPDATE Administrators SET username = :username, hashedPassword = :hashedPassword WHERE id = :id;";
$this->con->executeQuery(
$query,
array(
@ -71,7 +69,7 @@ class GatewayAdministrator
public function deleteAdministratorByID($id)
{
$query = "DELETE FROM Administrator WHERE id = :id;";
$query = "DELETE FROM Administrators WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
}
}

@ -11,7 +11,7 @@ class GatewayAnswer
public function addAnswer($answer)
{
$query = "insert into Answer(id,content) values (:id,:content);";
$query = "insert into Answers(id,content) values (:id,:content);";
$this->con->executeQuery(
$query,
array(
@ -23,7 +23,7 @@ class GatewayAnswer
public function getAnswerByIDQuestions($idQuestions)
{
$query = "SELECT * FROM answers, questions WHERE questions.id = :idQuestions;";
$query = "SELECT * FROM Answers, Questions WHERE questions.id = :idQuestions;";
$this->con->executeQuery($query, array(':idQuestions' => array($idQuestions, PDO::PARAM_INT)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -34,7 +34,7 @@ class GatewayAnswer
public function updateAnswer($answer)
{
$query = "UPDATE Answer SET content = :content WHERE id = :id;";
$query = "UPDATE Answers SET content = :content WHERE id = :id;";
$this->con->executeQuery(
$query,
array(
@ -46,7 +46,7 @@ class GatewayAnswer
public function deleteAnswer($id)
{
$query = "DELETE FROM Answer WHERE id = :id;";
$query = "DELETE FROM Answers WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
}
}

@ -11,7 +11,7 @@ class GatewayChapter
public function addChapter($chapter)
{
$query = "insert into Chapter(id,name) values (:id,:name);";
$query = "insert into Chapters(id,name) values (:id,:name);";
$this->con->executeQuery(
$query,
array(
@ -23,7 +23,7 @@ class GatewayChapter
public function getChapters()
{
$query = "SELECT * FROM Chapter;";
$query = "SELECT * FROM Chapters;";
$this->con->executeQuery($query);
$results = $this->con->getResults();
if ($results == NULL) {
@ -38,7 +38,7 @@ class GatewayChapter
public function updateChapter($chapter)
{
$query = "UPDATE Chapter SET name = :name WHERE id = :id;";
$query = "UPDATE Chapters SET name = :name WHERE id = :id;";
$this->con->executeQuery(
$query,
array(
@ -50,7 +50,7 @@ class GatewayChapter
public function deleteChapter($id)
{
$query = "DELETE FROM Chapter WHERE id = :id;";
$query = "DELETE FROM Chapters WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
}
}

@ -11,7 +11,7 @@ class GatewayPlayer
public function addPlayer($player)
{
$query = "insert into Player(id,nickname,hashedPassword) values (:id,:nickname,:hashedPassword);";
$query = "insert into Players(id,nickname,hashedPassword) values (:id,:nickname,:hashedPassword);";
$this->con->executeQuery(
$query,
array(
@ -24,7 +24,7 @@ class GatewayPlayer
public function getPlayerByNickname(string $nickname)
{
$query = "SELECT * FROM Player WHERE nickname = :nickname;";
$query = "SELECT * FROM Players WHERE nickname = :nickname;";
$this->con->executeQuery($query, array(':nickname' => array($nickname, PDO::PARAM_STR)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -34,7 +34,7 @@ class GatewayPlayer
}
public function getPlayerByID(int $id)
{
$query = "SELECT * FROM Player WHERE id = :id;";
$query = "SELECT * FROM Players WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -44,7 +44,7 @@ class GatewayPlayer
}
public function getPlayers()
{
$query = "SELECT * FROM Player;";
$query = "SELECT * FROM Players;";
$this->con->executeQuery($query);
$results = $this->con->getResults();
if ($results == NULL) {
@ -54,7 +54,7 @@ class GatewayPlayer
public function updatePlayer($player)
{
$query = "UPDATE Player SET nickname = :nickname, hashedPassword = :hashedPassword WHERE id = :id;";
$query = "UPDATE Players SET nickname = :nickname, hashedPassword = :hashedPassword WHERE id = :id;";
$this->con->executeQuery(
$query,
array(
@ -67,7 +67,7 @@ class GatewayPlayer
public function deletePlayerByID(int $id)
{
$query = "DELETE FROM Player WHERE id = :id;";
$query = "DELETE FROM Players WHERE id = :id;";
$this->con->executeQuery(
$query,
array(

@ -11,7 +11,7 @@ class GatewayQuestion
public function addQuestion($question)
{
$query = "insert into Question(id,content,difficulty,nbFails) values (:id,:content,:difficulty,:nbFails);";
$query = "insert into Questions(id,content,difficulty,nbFails) values (:id,:content,:difficulty,:nbFails);";
$this->con->executeQuery(
$query,
array(
@ -25,7 +25,7 @@ class GatewayQuestion
public function getQuestionByID($id)
{
$query = "SELECT * FROM Question WHERE id = :id;";
$query = "SELECT * FROM Questions WHERE id = :id;";
$this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
$results = $this->con->getResults();
if ($results == NULL) {
@ -36,7 +36,7 @@ class GatewayQuestion
public function getQuestions()
{
$query = "SELECT * FROM Question;";
$query = "SELECT * FROM Questions;";
$this->con->executeQuery($query);
$results = $this->con->getResults();
if ($results == NULL) {

@ -10,7 +10,3 @@ require_once(__DIR__ . '/usages/Autoload.php');
Autoload::charger();
$controller = new FrontController();
//require_once("vues/Acceuil.php");
require_once("vues/Acceuil.php");

@ -0,0 +1,300 @@
<?php
/*
MIT License
Copyright (c) 2012 Danny van Kooten <hi@dannyvankooten.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class AltoRouter
{
/**
* @var array Array of all routes (incl. named routes).
*/
protected $routes = [];
/**
* @var array Array of all named routes.
*/
protected $namedRoutes = [];
/**
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/
protected $basePath = '';
/**
* @var array Array of default match types (regex helpers)
*/
protected $matchTypes = [
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
];
/**
* Create router in one call from config.
*
* @param array $routes
* @param string $basePath
* @param array $matchTypes
* @throws Exception
*/
public function __construct(array $routes = [], string $basePath = '', array $matchTypes = [])
{
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
}
/**
* Retrieves all routes.
* Useful if you want to process or display routes.
* @return array All routes.
*/
public function getRoutes(): array
{
return $this->routes;
}
/**
* Add multiple routes at once from array in the following format:
*
* $routes = [
* [$method, $route, $target, $name]
* ];
*
* @param array $routes
* @return void
* @author Koen Punt
* @throws Exception
*/
public function addRoutes($routes)
{
if (!is_array($routes) && !$routes instanceof Traversable) {
throw new RuntimeException('Routes should be an array or an instance of Traversable');
}
foreach ($routes as $route) {
call_user_func_array([$this, 'map'], $route);
}
}
/**
* Set the base path.
* Useful if you are running your application from a subdirectory.
* @param string $basePath
*/
public function setBasePath(string $basePath)
{
$this->basePath = $basePath;
}
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* @param array $matchTypes The key is the name and the value is the regex.
*/
public function addMatchTypes(array $matchTypes)
{
$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
}
/**
* Map a route to a target
*
* @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE)
* @param string $route The route regex, custom regex must start with an @. You can use multiple pre-set regex filters, like [i:id]
* @param mixed $target The target where this route should point to. Can be anything.
* @param string $name Optional name of this route. Supply if you want to reverse route this url in your application.
* @throws Exception
*/
public function map(string $method, string $route, $target, string $name = null)
{
$this->routes[] = [$method, $route, $target, $name];
if ($name) {
if (isset($this->namedRoutes[$name])) {
throw new RuntimeException("Can not redeclare route '{$name}'");
}
$this->namedRoutes[$name] = $route;
}
}
/**
* Reversed routing
*
* Generate the URL for a named route. Replace regexes with supplied parameters
*
* @param string $routeName The name of the route.
* @param array $params Associative array of parameters to replace placeholders with.
* @return string The URL of the route with named parameters in place.
* @throws Exception
*/
public function generate(string $routeName, array $params = []): string
{
// Check if named route exists
if (!isset($this->namedRoutes[$routeName])) {
throw new RuntimeException("Route '{$routeName}' does not exist.");
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
// prepend base path to route url again
$url = $this->basePath . $route;
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach ($matches as $index => $match) {
list($block, $pre, $type, $param, $optional) = $match;
if ($pre) {
$block = substr($block, 1);
}
if (isset($params[$param])) {
// Part is found, replace for param value
$url = str_replace($block, $params[$param], $url);
} elseif ($optional && $index !== 0) {
// Only strip preceding slash if it's not at the base
$url = str_replace($pre . $block, '', $url);
} else {
// Strip match block
$url = str_replace($block, '', $url);
}
}
}
return $url;
}
/**
* Match a given Request Url against stored routes
* @param string $requestUrl
* @param string $requestMethod
* @return array|boolean Array with route information on success, false on failure (no match).
*/
public function match(string $requestUrl = null, string $requestMethod = null)
{
$params = [];
// set Request Url if it isn't passed as parameter
if ($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
$lastRequestUrlChar = $requestUrl ? $requestUrl[strlen($requestUrl)-1] : '';
// set Request Method if it isn't passed as a parameter
if ($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
foreach ($this->routes as $handler) {
list($methods, $route, $target, $name) = $handler;
$method_match = (stripos($methods, $requestMethod) !== false);
// Method did not match, continue to next route.
if (!$method_match) {
continue;
}
if ($route === '*') {
// * wildcard (matches all)
$match = true;
} elseif (isset($route[0]) && $route[0] === '@') {
// @ regex delimiter
$pattern = '`' . substr($route, 1) . '`u';
$match = preg_match($pattern, $requestUrl, $params) === 1;
} elseif (($position = strpos($route, '[')) === false) {
// No params in url, do string comparison
$match = strcmp($requestUrl, $route) === 0;
} else {
// Compare longest non-param string with url before moving on to regex
// Check if last character before param is a slash, because it could be optional if param is optional too (see https://github.com/dannyvankooten/AltoRouter/issues/241)
if (strncmp($requestUrl, $route, $position) !== 0 && ($lastRequestUrlChar === '/' || $route[$position-1] !== '/')) {
continue;
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params) === 1;
}
if ($match) {
if ($params) {
foreach ($params as $key => $value) {
if (is_numeric($key)) {
unset($params[$key]);
}
}
}
return [
'target' => $target,
'params' => $params,
'name' => $name
];
}
}
return false;
}
/**
* Compile the regex for a given route (EXPENSIVE)
* @param string $route
* @return string
*/
protected function compileRoute(string $route): string
{
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes;
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';
}
$optional = $optional !== '' ? '?' : null;
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. ')'
. $optional
. ')'
. $optional;
$route = str_replace($block, $pattern, $route);
}
}
return "`^$route$`u";
}
}

@ -1,6 +1,5 @@
<?php
//préfixe
$rep = __DIR__ . '/../';
//BD
@ -9,7 +8,7 @@ $pass = 'educ3306*';
$dsn = 'mysql:host=b62383e.online-server.cloud:3306;dbname=mathseduc';
//Vues
$vues["Solo"]="vues/Solo.php";
$vues["Multi"]="vues/Multi.php";
$vues["Accueil"]="vues/Accueil.php";
$vues["Connexion"]="vues/Connexion.php";
$vues["solo"]="vues/solo.php";
$vues["multi"]="vues/multijoueur.php";
$vues["accueil"]="vues/accueil.php";
$vues["connexion"]="vues/connexion.php";

@ -19,6 +19,7 @@
</head>
<body style="background: linear-gradient(to bottom, rgba(37, 34, 71, 1), rgba(37, 35, 72, 1));" class="col my-auto">
<h1>Toto</h1>
<div class="container text-center">
<div class="container text-center text-white border border-white rounded mt-5">
<p class="fs-2">

@ -21,21 +21,21 @@
<body style="background: linear-gradient(to bottom, rgba(37, 34, 71, 1), rgba(37, 35, 72, 1));">
<div class="d-flex flex-column align-items-center justify-content-between" style="height:95vh">
<img src="Media/Logo.png" style="margin-top:50px; object-fit:fill;" class="h-25">
<a href="vues/Solo.php" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:green;text-decoration: none;color: black; height:20vh;">
<a href="/solo" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:green;text-decoration: none;color: black; height:20vh;">
<div class="container text-center d-flex align-items-center text-center">
<h1 class="mx-auto fs-1">
SOLO
</h1>
</div>
</a>
<a href="vues/Multijoueur.php" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:orange;text-decoration: none;color: black;height:20vh;">
<a href="/multi" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:orange;text-decoration: none;color: black;height:20vh;">
<div class="container text-center d-flex align-items-center text-center">
<h1 class="mx-auto fs-1">
MULTIJOUEUR
</h1>
</div>
</a>
<a href="vues/AddQuestions.php" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:blue;text-decoration: none;color: black;height:20vh;">
<a href="/addquestions" class="text-white m-3 container text-center d-flex align-items-center w-75 rounded border border-white text-center" style="background-color:blue;text-decoration: none;color: black;height:20vh;">
<div class="container text-center d-flex align-items-center text-center">
<h1 class="mx-auto fs-1">
ajouter des questions
Loading…
Cancel
Save