FIX: Correction des principaux warnings de tout les fichiers.

J'ai corrigé tout ce qui s'apparente à un warning (il reste les unused variable mais tout le reste est OK).

PS: ON CODE EN PHP 7.4 !
pull/7/head
Tom 1 year ago
parent c1b10a7b88
commit 0d872490b5

@ -2,11 +2,15 @@
<module type="WEB_MODULE" version="4"> <module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/project/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/project/src/config" isTestSource="false" packagePrefix="config\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/exception" isTestSource="false" packagePrefix="model" /> <sourceFolder url="file://$MODULE_DIR$/project/src/controller" isTestSource="false" packagePrefix="controller\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/gateways" isTestSource="false" packagePrefix="model" /> <sourceFolder url="file://$MODULE_DIR$/project/src/model" isTestSource="false" packagePrefix="model\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/mdl" isTestSource="false" packagePrefix="model" /> <sourceFolder url="file://$MODULE_DIR$/project/src/model/exception" isTestSource="false" packagePrefix="model\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/metier" isTestSource="false" packagePrefix="model" /> <sourceFolder url="file://$MODULE_DIR$/project/src/model/gateways" isTestSource="false" packagePrefix="model\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/mdl" isTestSource="false" packagePrefix="model\" />
<sourceFolder url="file://$MODULE_DIR$/project/src/model/metier" isTestSource="false" packagePrefix="model\" />
<excludeFolder url="file://$MODULE_DIR$/project/src/vendor/altorouter/altorouter" />
<excludeFolder url="file://$MODULE_DIR$/project/src/vendor/composer" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />

@ -10,6 +10,12 @@
<option name="highlightLevel" value="WARNING" /> <option name="highlightLevel" value="WARNING" />
<option name="transferred" value="true" /> <option name="transferred" value="true" />
</component> </component>
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/project/src/vendor/altorouter/altorouter" />
<path value="$PROJECT_DIR$/project/src/vendor/composer" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.4"> <component name="PhpProjectSharedConfiguration" php_language_level="7.4">
<option name="suggestChangeDefaultLanguageLevel" value="false" /> <option name="suggestChangeDefaultLanguageLevel" value="false" />
</component> </component>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="VcsDirectoryMappings"> <component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" /> <mapping directory="" vcs="Git" />
</component> </component>
</project> </project>

@ -1,3 +1,3 @@
# Neutral # SCIENCEQUEST
Mise en situation d'une entreprise fictive établissant un lien avec un Product Owner (PO) ayant pour but de réaliser son projet durant 100 heures dédiées tout au long de l'année. Mise en situation d'une entreprise fictive établissant un lien avec un Product Owner (PO) ayant pour but de réaliser son projet durant 100 heures dédiées tout au long de l'année.

@ -2,6 +2,9 @@
namespace config; namespace config;
use model\ConfigurationJeu;
use model\Joueur;
use model\MdlPendu;
use model\ValidationException; use model\ValidationException;
class Validation class Validation
@ -22,13 +25,13 @@ class Validation
} }
if ($difficulty == '' || !filter_var($difficulty, FILTER_VALIDATE_INT)) { if ($difficulty == '' || !filter_var($difficulty, FILTER_VALIDATE_INT)) {
$dVueErreur[] = "Aucune difficultée séléctionnée"; $dVueErreur[] = "Aucune difficulté séléctionnée";
$difficulty = 0; $difficulty = 0;
throw new ValidationException("Erreur difficulté"); throw new ValidationException("Erreur difficulté");
} }
} }
public static function valUserLogin(string &$user, &$dVueErreur) public static function valUserLogin(string $user, &$dVueErreur)
{ {
if ($user == '' || !filter_var($user, FILTER_SANITIZE_STRING)) { if ($user == '' || !filter_var($user, FILTER_SANITIZE_STRING)) {
$dVueErreur[] = 'Identifiant invalide'; $dVueErreur[] = 'Identifiant invalide';
@ -37,7 +40,8 @@ class Validation
} }
} }
public static function valCodeInvitation(string &$codeInvitation, &$dVueErreur){ public static function valCodeInvitation(string $codeInvitation, &$dVueErreur): string
{
if($codeInvitation == ''){ if($codeInvitation == ''){
$dVueErreur[] = 'Code d\'invitation invalide'; $dVueErreur[] = 'Code d\'invitation invalide';
throw new ValidationException("Code d'invitation invalide"); throw new ValidationException("Code d'invitation invalide");
@ -56,8 +60,9 @@ class Validation
return $pseudo; return $pseudo;
} }
public static function valRole(&$role, &$dVueErreur){ public static function valRole(&$role, &$dVueErreur): Joueur
if(! $role instanceof \model\Joueur){ {
if(! $role instanceof Joueur){
$role = NULL; $role = NULL;
$dVueErreur[] = 'Role invalide'; $dVueErreur[] = 'Role invalide';
throw new ValidationException('Role invalide'); throw new ValidationException('Role invalide');
@ -65,8 +70,9 @@ class Validation
return $role; return $role;
} }
public static function valConfigurationJeu(&$configurationJeu, &$dVueErreur){ public static function valConfigurationJeu($configurationJeu, &$dVueErreur): ConfigurationJeu
if(! $configurationJeu instanceof \model\ConfigurationJeu){ {
if(! $configurationJeu instanceof ConfigurationJeu){
$role = NULL; $role = NULL;
$dVueErreur[] = 'Configuration du jeu invalide'; $dVueErreur[] = 'Configuration du jeu invalide';
throw new ValidationException('Configuration du jeu'); throw new ValidationException('Configuration du jeu');
@ -74,8 +80,9 @@ class Validation
return $configurationJeu; return $configurationJeu;
} }
public static function valMdlPendu(&$pendu, &$dVueErreur){ public static function valMdlPendu($pendu, &$dVueErreur): MdlPendu
if(! $pendu instanceof \model\MdlPendu){ {
if(! $pendu instanceof MdlPendu){
$role = NULL; $role = NULL;
$dVueErreur[] = 'Erreur mauvais jeu en utilisation'; $dVueErreur[] = 'Erreur mauvais jeu en utilisation';
throw new ValidationException('Erreur mauvais jeu en utilisation'); throw new ValidationException('Erreur mauvais jeu en utilisation');

@ -1,42 +1,42 @@
<?php <?php
namespace controller; namespace controller;
use Exception; use Exception;
use PDOException;
//gerer la connexion des admins //gerer la connexion des admins
class AdminController { class AdminController {
public function __construct(string $action){ public function __construct(string $action){
global $twig; global $twig;
//on initialise un tableau d'erreur pour etre utilisé par la vue erreur //on initialise un tableau d'erreur pour être utilisé par la vue erreur
$dVueEreur = []; $dVueErreur = [];
//verifier si l'utilisateur est connecté et admin //verifier si l'utilisateur est connecté et admin
if(isset($_SESSION["isAdmin"])){ if(isset($_SESSION["isAdmin"])){
if($_SESSION["isAdmin"]==true){ if($_SESSION["isAdmin"]) {
//donner la page admin a l'admin
try { try {
switch ($action) { switch ($action) {
case '': case '':
echo "accueil admin";exit; echo "accueil admin";
exit;
// echo $twig->render('admin/accueil.html'); // echo $twig->render('admin/accueil.html');
break;
case 'stats': case 'stats':
echo "stats admin";exit; echo "stats admin";
exit;
// echo $twig->render('admin/stats.html'); // echo $twig->render('admin/stats.html');
break;
case 'ajouterScientifiques': case 'ajouterScientifiques':
echo "page ajout scientifiques admin";exit; echo "page ajout scientifiques admin";
exit;
// echo $twig->render('admin/ajouter.html'); // echo $twig->render('admin/ajouter.html');
break;
//mauvaise action //mauvaise action
default: default:
$dVueErreur[] = "Erreur d'appel php"; $dVueErreur[] = "Erreur d'appel php";
echo $twig->render('accueil.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('accueil.html', ['dVueErreur' => $dVueErreur]);
break; break;
} }
} catch (\PDOException $e) { } catch (PDOException $e) {
$dVueErreur[] = 'Erreur avec la base de données !'; $dVueErreur[] = 'Erreur avec la base de données !';
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
} catch (\Exception $e2) { } catch (Exception $e2) {
$dVueErreur[] = 'Erreur inattendue !'; $dVueErreur[] = 'Erreur inattendue !';
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
} }
@ -44,9 +44,9 @@ class AdminController {
} }
//verifier si l'utilisateur est connecté mais pas admin //verifier si l'utilisateur est connecté mais pas admin
if(isset($_SESSION["isLogged"])){ if(isset($_SESSION["isLogged"])){
if($_SESSION["isLogged"]==true) { if($_SESSION["isLogged"]) {
//dire acces interdit au non admins //dire acces interdit aux non admins
array_push($dVueEreur, "Erreur 403 : Acces interdit"); $dVueErreur[] = "Erreur 403 : Acces interdit";
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
exit(0); exit(0);
} }
@ -56,4 +56,3 @@ class AdminController {
exit(0); exit(0);
} }
} }
?>

@ -1,16 +1,27 @@
<?php <?php
namespace controller; namespace controller;
use AltoRouter;
use config\Validation; use config\Validation;
use Exception;
use http\Params; use http\Params;
use model\ConfigurationJeu;
use model\Connection; use model\Connection;
use model\LoginException; use model\LoginException;
use model\MdlAdmin; use model\MdlAdmin;
use model\MdlDifficulte;
use model\MdlJeu;
use model\MdlUser; use model\MdlUser;
use model\ValidationException;
use PDOException;
class FrontController class FrontController
{ {
private Connection $con; private Connection $con;
/**
* @throws Exception
*/
public function __construct() public function __construct()
{ {
@ -18,7 +29,7 @@ class FrontController
global $basePath; global $basePath;
//altorouter //altorouter
$router = new \AltoRouter(); $router = new AltoRouter();
$router->setBasePath($basePath); $router->setBasePath($basePath);
$router->map('GET|POST','/[a:action]?','UserController'); $router->map('GET|POST','/[a:action]?','UserController');
@ -42,7 +53,7 @@ class FrontController
$match = $router->match(); $match = $router->match();
if (!$match) { if (!$match) {
throw new \Exception('Wrong call'); throw new Exception('Wrong call');
} }
switch($match['target']) { switch($match['target']) {
@ -57,6 +68,7 @@ class FrontController
$action = 'login'; $action = 'login';
} }
$this->callController('AdminController',$action); $this->callController('AdminController',$action);
break;
case 'PseudoController': case 'PseudoController':
$this->callController('PseudoController',$match); $this->callController('PseudoController',$match);
@ -72,14 +84,14 @@ class FrontController
echo $twig->render('accueil.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('accueil.html', ['dVueErreur' => $dVueErreur]);
break; break;
} }
} catch (\PDOException $e) { } catch (PDOException $e) {
$dVueErreur[] = 'Erreur avec la base de données !'; $dVueErreur[] = 'Erreur avec la base de données !';
$dVueErreur[] = $e->getMessage(); $dVueErreur[] = $e->getMessage();
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
} catch (LoginException $e) { } catch (LoginException $e) {
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
echo $twig->render('login.html'); echo $twig->render('login.html');
} catch (\Exception $e2) { } catch (Exception $e2) {
$dVueErreur[] = 'Erreur inattendue !'.$e2->getMessage(); $dVueErreur[] = 'Erreur inattendue !'.$e2->getMessage();
echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]); echo $twig->render('erreur.html', ['dVueErreur' => $dVueErreur]);
} }
@ -108,17 +120,15 @@ class FrontController
$id_jeu = $_POST['jeu'] ?? ''; $id_jeu = $_POST['jeu'] ?? '';
$id_difficulte = $_POST['difficulte'] ?? ''; $id_difficulte = $_POST['difficulte'] ?? '';
try{ try{
\config\Validation::val_form($id_jeu, $id_difficulte, $dVueErreur); Validation::val_form($id_jeu, $id_difficulte, $dVueErreur);
}catch (\model\ValidationException $ex){ }catch (ValidationException|Exception $ex){
$this->CreateParty($dVueErreur);
}catch (\Exception $ex){
$this->CreateParty($dVueErreur); $this->CreateParty($dVueErreur);
} }
if(count($dVueErreur) == 0){ if(count($dVueErreur) == 0){
$jeu = (new \model\MdlJeu())->getFromId($id_jeu); $jeu = (new MdlJeu())->getFromId($id_jeu);
$difficulte = (new \model\MdlDifficulte())->getFromId($id_difficulte); $difficulte = (new MdlDifficulte())->getFromId($id_difficulte);
$_SESSION['configuration'] = new \model\ConfigurationJeu($jeu, $difficulte); $_SESSION['configuration'] = new ConfigurationJeu($jeu, $difficulte);
header("Location: /pseudo"); header("Location: /pseudo");
#echo $twig->render('accueil.html', ['dVue' => $dVue, 'dVueErreur' => $dVueErreur]); #echo $twig->render('accueil.html', ['dVue' => $dVue, 'dVueErreur' => $dVueErreur]);
@ -126,4 +136,8 @@ class FrontController
$this->CreateParty($dVueErreur); $this->CreateParty($dVueErreur);
} }
} }
private function CreateParty(array $dVueErreur)
{
}
} }

@ -7,6 +7,9 @@ use model\ValidationException;
class JouerController{ class JouerController{
/**
* @throws Exception
*/
public function __construct(){ public function __construct(){
global $twig, $config; global $twig, $config;
$dVue = []; $dVue = [];
@ -30,7 +33,6 @@ class JouerController{
break; break;
default: default:
throw new Exception("Jeu non défini !"); throw new Exception("Jeu non défini !");
break;
} }
} }
}else{ }else{

@ -3,8 +3,11 @@
namespace controller; namespace controller;
use config\Validation; use config\Validation;
use Exception;
use model\Connection; use model\Connection;
use model\GameGateway; use model\GameGateway;
use model\MdlDifficulte;
use model\MdlJeu;
use model\ValidationException; use model\ValidationException;
class UserController { class UserController {
@ -25,6 +28,9 @@ class UserController {
} }
} }
/**
* @throws Exception
*/
public function jouer(array $params) { public function jouer(array $params) {
global $twig, $config; global $twig, $config;
$dVue = []; $dVue = [];
@ -48,7 +54,6 @@ class UserController {
break; break;
default: default:
throw new Exception("Jeu non défini !"); throw new Exception("Jeu non défini !");
break;
} }
} }
}else{ }else{
@ -61,8 +66,8 @@ class UserController {
global $twig; global $twig;
global $dVueErreur; global $dVueErreur;
$listJeu = (new \model\MdlJeu())->getAll(); $listJeu = (new MdlJeu())->getAll();
$listDifficulte = (new \model\MdlDifficulte())->getAll(); $listDifficulte = (new MdlDifficulte())->getAll();
$dVueCreateJeu = []; $dVueCreateJeu = [];
foreach($listJeu as $jeu){ foreach($listJeu as $jeu){

@ -1,4 +1,3 @@
-- Testé sous pgsql 15 -- Testé sous pgsql 15
DROP TABLE IF EXISTS Reponse; DROP TABLE IF EXISTS Reponse;

@ -2,12 +2,13 @@
require_once(__DIR__.'/vendor/autoload.php'); require_once(__DIR__.'/vendor/autoload.php');
require_once(__DIR__.'/config/config.php'); require_once(__DIR__.'/config/config.php');
use controller\FrontController; use controller\FrontController;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
//twig //twig
$loader = new \Twig\Loader\FilesystemLoader('templates'); $loader = new FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [ $twig = new Environment($loader, [
'cache' => false, 'cache' => false,
]); ]);

@ -2,7 +2,9 @@
namespace model; namespace model;
class IdSessionDoubleException extends \RuntimeException use RuntimeException;
class IdSessionDoubleException extends RuntimeException
{ {
private int $idJoueur; private int $idJoueur;
private string $idSession; private string $idSession;

@ -2,6 +2,8 @@
namespace model; namespace model;
class LoginException extends \Exception use Exception;
class LoginException extends Exception
{ {
} }

@ -2,7 +2,9 @@
namespace model; namespace model;
class PseudoDejaPrisException extends \RuntimeException use RuntimeException;
class PseudoDejaPrisException extends RuntimeException
{ {
} }

@ -1,5 +1,7 @@
<?php <?php
namespace model; namespace model;
class ValidationException extends \RuntimeException{ use RuntimeException;
class ValidationException extends RuntimeException{
} }

@ -2,10 +2,13 @@
namespace model; namespace model;
use PDO;
use PDOStatement;
class AdminGateway class AdminGateway
{ {
private \PDO $con; private PDO $con;
private \PDOStatement $stmt; private PDOStatement $stmt;
public function __construct(Connection $con) public function __construct(Connection $con)
{ {
$this->con=$con; $this->con=$con;
@ -15,7 +18,7 @@ class AdminGateway
{ {
$sql = "SELECT * FROM Admin WHERE email=:email"; $sql = "SELECT * FROM Admin WHERE email=:email";
$this->con->executeQuery($sql, array( $this->con->executeQuery($sql, array(
':email' => array($email, \PDO::PARAM_STR) ':email' => array($email, PDO::PARAM_STR)
)); ));
$result = $this->con->getOneResult(); $result = $this->con->getOneResult();

@ -3,10 +3,11 @@
namespace model; namespace model;
use PDO; use PDO;
use PDOStatement;
class Connection extends PDO { class Connection extends PDO {
private $stmt; private PDOStatement $stmt;
public function __construct(string $dsn, string $username, string $password) { public function __construct(string $dsn, string $username, string $password) {

@ -4,7 +4,7 @@ namespace model;
class DifficulteGateway class DifficulteGateway
{ {
private $con; private Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;

@ -1,13 +1,14 @@
<?php <?php
namespace model; namespace model;
use PDO;
class GameGateway class GameGateway
{ {
private $con; private Connection $con;
function __construct(Connection $co) { function __construct(Connection $con) {
$this->con = $co; $this->con = $con;
} }
public static function getGames() : array public static function getGames() : array
{ {
@ -21,7 +22,7 @@ class GameGateway
public function getGameByCode(int $code) : array { public function getGameByCode(int $code) : array {
$query = 'SELECT * FROM Partie WHERE codeInvitation=:id'; $query = 'SELECT * FROM Partie WHERE codeInvitation=:id';
$this->con->executeQuery($query,array( $this->con->executeQuery($query,array(
':id' => array($code,\PDO::PARAM_INT) ':id' => [$code, PDO::PARAM_INT]
)); ));
return $this->con->getResults(); return $this->con->getResults();
} }

@ -9,23 +9,49 @@ class InviteGateway extends JoueurGateway
parent::__construct($con); parent::__construct($con);
} }
public function getFromIdSession($idSession): array|bool // public function getFromIdSession($idSession): array|bool // <- Seulement autorisé en PHP 8 /!\ (on est en 7.4)
{ // {
$this->con->executeQuery("SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE idSession = :idSession;", // $this->con->executeQuery("SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE idSession = :idSession;",
[":idSession" => [$idSession, $this->con::PARAM_STR]]); // [":idSession" => [$idSession, $this->con::PARAM_STR]]);
// return $this->con->getOneResult();
// }
/**
* @param string $idSession
* @return array|bool
*/
public function getFromIdSession(string $idSession) { // <- PHP 7.4
$this->con->executeQuery(
"SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE idSession = :idSession;",
[":idSession" => [$idSession, $this->con::PARAM_STR]]
);
return $this->con->getOneResult(); return $this->con->getOneResult();
} }
public function getFromId($id): array|bool
{
$this->con->executeQuery("SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE id = :id;", // public function getFromId($id): array|bool // <- Seulement autorisé en PHP 8 /!\ (on est en 7.4)
[":id" => [$id, $this->con::PARAM_INT]]); // {
// $this->con->executeQuery("SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE id = :id;",
// [":id" => [$id, $this->con::PARAM_INT]]);
// return $this->con->getOneResult();
// }
/**
* @param int $id
* @return array|bool
*/
public function getFromId(int $id) { // <- PHP 7.4
$this->con->executeQuery(
"SELECT idJoueur, pseudo, idSession FROM Invite JOIN Joueur ON id=idJoueur WHERE id = :id;",
[":id" => [$id, $this->con::PARAM_INT]]
);
return $this->con->getOneResult(); return $this->con->getOneResult();
} }
public function insertInvite(string $pseudo, string $idSession): int{ public function insertInvite(string $pseudo, string $idSession): int{
$row = $this->getFromIdSession($idSession); $row = $this->getFromIdSession($idSession);
if($row != false){ if($row){
throw new IdSessionDoubleException($row['idjoueur'], $row['idsession']); throw new IdSessionDoubleException($row['idjoueur'], $row['idsession']);
}else{ }else{
$id = $this->insertJoueur($pseudo); $id = $this->insertJoueur($pseudo);

@ -2,11 +2,9 @@
namespace model; namespace model;
use PDO;
class JeuGateway class JeuGateway
{ {
private $con; private Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;

@ -4,21 +4,33 @@ namespace model;
abstract class JoueurGateway abstract class JoueurGateway
{ {
protected $con; protected Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;
} }
protected function getFromPseudo($pseudo): array|bool // protected function getFromPseudo($pseudo): array|bool <- autorisé seulement en PHP 8
{ // {
$this->con->executeQuery("SELECT id, pseudo FROM Joueur WHERE pseudo = :pseudo;", // $this->con->executeQuery("SELECT id, pseudo FROM Joueur WHERE pseudo = :pseudo;",
[":pseudo" => [$pseudo, $this->con::PARAM_STR]]); // [":pseudo" => [$pseudo, $this->con::PARAM_STR]]);
// return $this->con->getOneResult();
// }
/**
* @param string $pseudo
* @return array|bool
*/
protected function getFromPseudo(string $pseudo) { // <- PHP 7.4
$this->con->executeQuery(
"SELECT id, pseudo FROM Joueur WHERE pseudo = :pseudo;",
[":pseudo" => [$pseudo, $this->con::PARAM_STR]]
);
return $this->con->getOneResult(); return $this->con->getOneResult();
} }
protected function insertJoueur(string $pseudo): int{ protected function insertJoueur(string $pseudo): int{
if($this->getFromPseudo($pseudo) != false){ if($this->getFromPseudo($pseudo)){
throw new PseudoDejaPrisException(); throw new PseudoDejaPrisException();
}else{ }else{
$this->con->executeQuery("INSERT INTO Joueur(pseudo) VALUES(:pseudo);", $this->con->executeQuery("INSERT INTO Joueur(pseudo) VALUES(:pseudo);",
@ -28,7 +40,7 @@ abstract class JoueurGateway
} }
public function setPseudo(int $id, string $pseudo){ public function setPseudo(int $id, string $pseudo){
if($this->getFromPseudo($pseudo) != false){ if($this->getFromPseudo($pseudo)){
throw new PseudoDejaPrisException(); throw new PseudoDejaPrisException();
}else{ }else{
$this->con->executeQuery("UPDATE Joueur SET pseudo=:pseudo WHERE id=:id", $this->con->executeQuery("UPDATE Joueur SET pseudo=:pseudo WHERE id=:id",

@ -4,15 +4,25 @@ namespace model;
class ScientifiqueGateway class ScientifiqueGateway
{ {
private $con; private Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;
} }
public function getRandom(): array|bool{ // public function getRandom(): array|bool{ <- autorisé seulement en PHP 8
// $this->con->executeQuery(
// "SELECT id, nom, prenom, photo, dateNaissance, descriptif, ratiotrouvee, idthematique, iddifficulte, index FROM Scientifique ORDER BY RANDOM() LIMIT 1;");
// return $this->con->getOneResult();
// }
/**
* @return array|bool
*/
public function getRandom() { // PHP 7.4
$this->con->executeQuery( $this->con->executeQuery(
"SELECT id, nom, prenom, photo, dateNaissance, descriptif, ratiotrouvee, idthematique, iddifficulte, idsexe FROM Scientifique ORDER BY RANDOM() LIMIT 1;"); "SELECT id, nom, prenom, photo, dateNaissance, descriptif, ratiotrouvee, idthematique, iddifficulte, idsexe FROM Scientifique ORDER BY RANDOM() LIMIT 1;"
);
return $this->con->getOneResult(); return $this->con->getOneResult();
} }
} }

@ -4,7 +4,7 @@ namespace model;
class SexeGateway class SexeGateway
{ {
private $con; private Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;

@ -4,7 +4,7 @@ namespace model;
class ThematiqueGateway class ThematiqueGateway
{ {
private $con; private Connection $con;
function __construct(Connection $con) { function __construct(Connection $con) {
$this->con = $con; $this->con = $con;

@ -2,10 +2,13 @@
namespace model; namespace model;
use PDO;
use PDOStatement;
class UserGateway class UserGateway
{ {
private Connection $con; private Connection $con;
private \PDOStatement $stmt; private PDOStatement $stmt;
public function __construct(Connection $con) public function __construct(Connection $con)
{ {
$this->con=$con; $this->con=$con;
@ -15,7 +18,7 @@ class UserGateway
{ {
$sql = "SELECT * FROM Utilisateur WHERE email=:email"; $sql = "SELECT * FROM Utilisateur WHERE email=:email";
$this->con->executeQuery($sql, array( $this->con->executeQuery($sql, array(
':email' => array($email, \PDO::PARAM_STR) ':email' => array($email, PDO::PARAM_STR)
)); ));
$result = $this->con->getOneResult(); $result = $this->con->getOneResult();
@ -27,7 +30,7 @@ class UserGateway
} }
public function addUser(string $email, string $password): void public function addUser(string $email, string $password): void
{ {
$sql = "INSERT INTO utilisateur (email, password) VALUES (:email, :password)"; $sql = "INSERT INTO Utilisateur (email, password) VALUES (:email, :password)";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':email', $email); $stmt->bindValue(':email', $email);
$stmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT)); $stmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
@ -35,14 +38,14 @@ class UserGateway
} }
public function deleteUser(int $id): void public function deleteUser(int $id): void
{ {
$sql = "DELETE FROM utilisateur WHERE id=:id"; $sql = "DELETE FROM Utilisateur WHERE idJoueur=:id";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':id', $id); $stmt->bindValue(':id', $id);
$stmt->execute(); $stmt->execute();
} }
public function updateUser(int $id, string $email, string $password): void public function updateUser(int $id, string $email, string $password): void
{ {
$sql = "UPDATE utilisateur SET email=:email, password=:password WHERE id=:id"; $sql = "UPDATE Utilisateur SET email=:email, password=:password WHERE idJoueur=:id";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':id', $id); $stmt->bindValue(':id', $id);
$stmt->bindValue(':email', $email); $stmt->bindValue(':email', $email);
@ -51,7 +54,7 @@ class UserGateway
} }
public function getUser(int $id): User public function getUser(int $id): User
{ {
$sql = "SELECT * FROM utilisateur WHERE id=:id"; $sql = "SELECT * FROM Utilisateur WHERE idJoueur=:id";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':id', $id); $stmt->bindValue(':id', $id);
$stmt->execute(); $stmt->execute();
@ -72,7 +75,7 @@ class UserGateway
} }
public function getHashedPasswordById(int $id): string public function getHashedPasswordById(int $id): string
{ {
$sql = "SELECT password FROM utilisateur WHERE id=:id"; $sql = "SELECT password FROM Utilisateur WHERE idJoueur=:id";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':id', $id); $stmt->bindValue(':id', $id);
$stmt->execute(); $stmt->execute();
@ -81,7 +84,7 @@ class UserGateway
} }
public function getHashedPassword(int $email): string public function getHashedPassword(int $email): string
{ {
$sql = "SELECT password FROM utilisateur WHERE email=:email"; $sql = "SELECT password FROM Utilisateur WHERE email=:email";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':email', $email); $stmt->bindValue(':email', $email);
$stmt->execute(); $stmt->execute();
@ -90,7 +93,7 @@ class UserGateway
} }
public function getUserId(string $email): int public function getUserId(string $email): int
{ {
$sql = "SELECT id FROM utilisateur WHERE email=:email"; $sql = "SELECT idJoueur FROM Utilisateur WHERE email=:email";
$stmt = $this->con->prepare($sql); $stmt = $this->con->prepare($sql);
$stmt->bindValue(':email', $email); $stmt->bindValue(':email', $email);
$stmt->execute(); $stmt->execute();

@ -13,7 +13,8 @@ class MdlAdmin extends MdlBase{
return $this->gw->login($username, $password); return $this->gw->login($username, $password);
} }
public static function isAdmin() { public static function isAdmin(): bool
{
if(!isset($_SESSION['admin']) if(!isset($_SESSION['admin'])
|| !$_SESSION['admin'] || !$_SESSION['admin']
|| !isset($_SESSION['email']) || !isset($_SESSION['email'])

@ -10,11 +10,12 @@ class MdlPendu{
private array $lettreExceptees; private array $lettreExceptees;
private array $lettreUtilisees; private array $lettreUtilisees;
private static $nbFailsMax = 8; private static int $nbFailsMax = 8;
public function __construct(Scientifique $scientifiqueATrouver){ public function __construct(Scientifique $scientifiqueATrouver){
$this->scientifiqueATrouver = $scientifiqueATrouver; $this->scientifiqueATrouver = $scientifiqueATrouver;
$this->aTrouver = strtr($scientifiqueATrouver->getPrenom()." ".$scientifiqueATrouver->getNom(), 'áàâäãåçéèêëíìîïñóòôöõúùûüýÿ', 'aaaaaaceeeeiiiinooooouuuuyy'); #suppression des accents $this->aTrouver = iconv('UTF-8', 'ASCII//TRANSLIT', $scientifiqueATrouver->getPrenom()." ".$scientifiqueATrouver->getNom()); #suppression des accents
$this->aTrouver = preg_replace('/[^A-Za-z0-9 ]/', '', $this->aTrouver); // Retire les caractères non-alphanumeric
$this->nbFail = 0; $this->nbFail = 0;
$this->nbTours = 0; $this->nbTours = 0;
$this->lettreExceptees = [' ', '-']; $this->lettreExceptees = [' ', '-'];
@ -24,13 +25,18 @@ class MdlPendu{
public function jouerLettre(string $lettre): string{ public function jouerLettre(string $lettre): string{
$lettre = strtolower($lettre); $lettre = strtolower($lettre);
if(strlen($lettre) != 1){ throw new ValidationException("Veuillez fournir une seule lettre");} if(strlen($lettre) != 1){ throw new ValidationException("Veuillez fournir une seule lettre");}
if(!ctype_alpha($lettre)){ throw new ValidationException("Veuillez fournir une caractère alphabétique");} if(!ctype_alpha($lettre)){ throw new ValidationException("Veuillez fournir un caractère alphabétique");}
if(in_array($lettre, $this->lettreUtilisees)){ throw new ValidationException("Vous avez déjà joué cette lettre");} if(in_array($lettre, $this->lettreUtilisees)){ throw new ValidationException("Vous avez déjà joué cette lettre");}
$this->nbTours += 1; $this->nbTours += 1;
if(!str_contains($this->aTrouver, $lettre)){ // if(!str_contains($this->aTrouver, $lettre)){ // UNIQUEMENT EN PHP 8.0
// $this->nbFail += 1;
// }
if (strpos($this->aTrouver, $lettre) === false) { // PHP 7.4
$this->nbFail += 1; $this->nbFail += 1;
} }
$this->lettreUtilisees[] = $lettre; $this->lettreUtilisees[] = $lettre;
return $this->getDecouvert(); return $this->getDecouvert();
} }

@ -3,6 +3,7 @@
namespace model; namespace model;
use DateTime; use DateTime;
use Exception;
use RuntimeException; use RuntimeException;
class MdlScientifique extends MdlBase{ class MdlScientifique extends MdlBase{
@ -19,9 +20,12 @@ class MdlScientifique extends MdlBase{
$this->mdlThematique = new MdlThematique(); $this->mdlThematique = new MdlThematique();
} }
/**
* @throws Exception
*/
public function getRandom(): Scientifique{ public function getRandom(): Scientifique{
$row = $this->gw->getRandom(); $row = $this->gw->getRandom();
if($row == false) throw new RuntimeException("Erreur aucun scientifique trouvé"); if(!$row) throw new RuntimeException("Erreur aucun scientifique trouvé");
$sexe = $this->mdlSexe->getFromId($row['idsexe']); $sexe = $this->mdlSexe->getFromId($row['idsexe']);
$difficulte = $this->mdlDifficulte->getFromId($row['iddifficulte']); $difficulte = $this->mdlDifficulte->getFromId($row['iddifficulte']);
$thematique = $this->mdlThematique->getFromId($row['idthematique']); $thematique = $this->mdlThematique->getFromId($row['idthematique']);

@ -2,9 +2,12 @@
namespace model; namespace model;
enum Difficulty class Difficulty
{ {
case Easy; const EASY = 'Easy';
case Medium; const MEDIUM = 'Medium';
case Hard; const HARD = 'Hard';
} }
// Usage
// $difficulty = Difficulty::EASY;

@ -11,7 +11,7 @@ class Jeu
/** /**
* @param int $id * @param int $id
* @param string $nom * @param string $nom
* @param string $nbParties * @param int $nbrParties
*/ */
public function __construct(int $id, string $nom, int $nbrParties) public function __construct(int $id, string $nom, int $nbrParties)
{ {

@ -22,7 +22,9 @@ class Scientifique
* @param string $nom * @param string $nom
* @param string $prenom * @param string $prenom
* @param string $photo * @param string $photo
* @param DateTime $dateNaiss
* @param string $descriptif * @param string $descriptif
* @param float $ratioTrouvee
* @param Thematique $thematique * @param Thematique $thematique
* @param Difficulte $difficulte * @param Difficulte $difficulte
* @param Sexe $sexe * @param Sexe $sexe

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
<style> <style>
body { body {
margin: 10px; margin: 10px;
@ -36,6 +36,6 @@
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Créer une partie</title> <title>Créer une partie</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
<style> <style>
p, p,
label { label {
@ -23,7 +23,7 @@
<br><br><br> <br><br><br>
<center> <center>
<p>Pour créer votre partie, merci de faire vos choix et de cliquer sur valider</p> <p>Pour créer voter partie, merci de faire vos choix et de cliquer sur valider</p>
<form action="validationFormulaire" method="post"> <form action="validationFormulaire" method="post">
<fieldset> <fieldset>
<legend>Mini-jeux disponibles</legend> <legend>Mini-jeux disponibles</legend>
@ -61,6 +61,6 @@
</form> </form>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,13 +3,13 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Rejoindre une partie</title> <title>Rejoindre une partie</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
</head> </head>
<body> <body>
<h1>Rejoindre une partie</h1> <h1>Rejoindre une partie</h1>
<center> <center>
<p>Merci de vous munir de votre code de partie et de l'entrer dans le champ ci-dessous</p> <p>Merci de vous munir de votre code de partie</p>
<form action="#" method="post"> <form action="#" method="post">
<label for="codeInvitation">Code de la partie</label> <label for="codeInvitation">Code de la partie</label>
<input type="text" name="codeInvitation" id="codeInvitation"> <input type="text" name="codeInvitation" id="codeInvitation">
@ -24,6 +24,6 @@
</div> </div>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Se connecter</title> <title>Se connecter</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
</head> </head>
<body> <body>
<h1>Se connecter</h1> <h1>Se connecter</h1>
@ -14,7 +14,9 @@
<input type="text" name="login" id="login"> <input type="text" name="login" id="login">
<br> <br>
<label for="login">Mot de passe</label><br> <label for="login">Mot de passe</label><br>
<label for="password">
<input type="password" name="password" id="password"> <input type="password" name="password" id="password">
</label>
<br><br> <br><br>
<input type="submit" value="Valider"> <input type="submit" value="Valider">
{ % for error in dErreur % } { % for error in dErreur % }
@ -26,6 +28,6 @@
</form> </form>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Pendu</title> <title>Pendu</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
<style> <style>
p, p,
label { label {
@ -54,7 +54,9 @@
</div> </div>
{% endif %} {% endif %}
<div> <div>
<label>
<input required type="text" name="lettre"> <input required type="text" name="lettre">
</label>
</div> </div>
</fieldset> </fieldset>
<input type="submit" value="Valider"> <input type="submit" value="Valider">
@ -62,6 +64,6 @@
</form> </form>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Pendu - Score</title> <title>Pendu - Score</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
<style> <style>
p, p,
label { label {
@ -44,6 +44,6 @@
<a href=".">Retour à l'accueil</a> <a href=".">Retour à l'accueil</a>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Saisir Pseudo</title> <title>Saisir Pseudo</title>
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="../css/bootstrap.min.css">
<style> <style>
p, p,
label { label {
@ -35,7 +35,9 @@
</div> </div>
{% endif %} {% endif %}
<div> <div>
<label for="txt_pseudo">
<input required type="text" name="pseudo" id="txt_pseudo"> <input required type="text" name="pseudo" id="txt_pseudo">
</label>
</div> </div>
</fieldset> </fieldset>
<input type="submit" value="Valider"> <input type="submit" value="Valider">
@ -43,6 +45,6 @@
</form> </form>
</center> </center>
<script src="js/bootstrap.min.js"></script> <script src="../js/bootstrap.min.js"></script>
</body> </body>
</html> </html>

@ -17,22 +17,22 @@ class AltoRouter
/** /**
* @var array Array of all routes (incl. named routes). * @var array Array of all routes (incl. named routes).
*/ */
protected $routes = []; protected array $routes = [];
/** /**
* @var array Array of all named routes. * @var array Array of all named routes.
*/ */
protected $namedRoutes = []; protected array $namedRoutes = [];
/** /**
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host) * @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/ */
protected $basePath = ''; protected string $basePath = '';
/** /**
* @var array Array of default match types (regex helpers) * @var array Array of default match types (regex helpers)
*/ */
protected $matchTypes = [ protected array $matchTypes = [
'i' => '[0-9]++', 'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++', 'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++', 'h' => '[0-9A-Fa-f]++',
@ -49,7 +49,7 @@ class AltoRouter
* @param array $matchTypes * @param array $matchTypes
* @throws Exception * @throws Exception
*/ */
public function __construct(array $routes = [], $basePath = '', array $matchTypes = []) public function __construct(array $routes = [], string $basePath = '', array $matchTypes = [])
{ {
$this->addRoutes($routes); $this->addRoutes($routes);
$this->setBasePath($basePath); $this->setBasePath($basePath);
@ -61,7 +61,7 @@ class AltoRouter
* Useful if you want to process or display routes. * Useful if you want to process or display routes.
* @return array All routes. * @return array All routes.
*/ */
public function getRoutes() public function getRoutes(): array
{ {
return $this->routes; return $this->routes;
} }
@ -75,14 +75,14 @@ class AltoRouter
* *
* @param array $routes * @param array $routes
* @return void * @return void
* @author Koen Punt
* @throws Exception * @throws Exception
*@author Koen Punt
*/ */
public function addRoutes($routes) public function addRoutes(array $routes)
{ {
if (!is_array($routes) && !$routes instanceof Traversable) { // if (!is_array($routes) && !$routes instanceof Traversable) {
throw new RuntimeException('Routes should be an array or an instance of Traversable'); // throw new RuntimeException('Routes should be an array or an instance of Traversable');
} // }
foreach ($routes as $route) { foreach ($routes as $route) {
call_user_func_array([$this, 'map'], $route); call_user_func_array([$this, 'map'], $route);
} }
@ -93,7 +93,7 @@ class AltoRouter
* Useful if you are running your application from a subdirectory. * Useful if you are running your application from a subdirectory.
* @param string $basePath * @param string $basePath
*/ */
public function setBasePath($basePath) public function setBasePath(string $basePath)
{ {
$this->basePath = $basePath; $this->basePath = $basePath;
} }
@ -114,22 +114,20 @@ class AltoRouter
* @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE) * @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 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 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. * @param string|null $name Optional name of this route. Supply if you want to reverse route this url in your application.
* @throws Exception * @throws Exception
*/ */
public function map($method, $route, $target, $name = null) public function map(string $method, string $route, $target, string $name = null)
{ {
$this->routes[] = [$method, $route, $target, $name]; $this->routes[] = [$method, $route, $target, $name];
if ($name) { if ($name) {
if (isset($this->namedRoutes[$name])) { if (isset($this->namedRoutes[$name])) {
throw new RuntimeException("Can not redeclare route '{$name}'"); throw new RuntimeException("Can not redeclare route '$name'");
} }
$this->namedRoutes[$name] = $route; $this->namedRoutes[$name] = $route;
} }
return;
} }
/** /**
@ -138,16 +136,16 @@ class AltoRouter
* Generate the URL for a named route. Replace regexes with supplied parameters * Generate the URL for a named route. Replace regexes with supplied parameters
* *
* @param string $routeName The name of the route. * @param string $routeName The name of the route.
* @param array @params Associative array of parameters to replace placeholders with. * @param array $params @params Associative array of parameters to replace placeholders with.
* @return string The URL of the route with named parameters in place. * @return string The URL of the route with named parameters in place.
* @throws Exception * @throws Exception
*/ */
public function generate($routeName, array $params = []) public function generate(string $routeName, array $params = []): string
{ {
// Check if named route exists // Check if named route exists
if (!isset($this->namedRoutes[$routeName])) { if (!isset($this->namedRoutes[$routeName])) {
throw new RuntimeException("Route '{$routeName}' does not exist."); throw new RuntimeException("Route '$routeName' does not exist.");
} }
// Replace named parameters // Replace named parameters
@ -156,7 +154,7 @@ class AltoRouter
// prepend base path to route url again // prepend base path to route url again
$url = $this->basePath . $route; $url = $this->basePath . $route;
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach ($matches as $index => $match) { foreach ($matches as $index => $match) {
list($block, $pre, $type, $param, $optional) = $match; list($block, $pre, $type, $param, $optional) = $match;
@ -182,18 +180,18 @@ class AltoRouter
/** /**
* Match a given Request Url against stored routes * Match a given Request Url against stored routes
* @param string $requestUrl * @param string|null $requestUrl
* @param string $requestMethod * @param string|null $requestMethod
* @return array|boolean Array with route information on success, false on failure (no match). * @return array|boolean Array with route information on success, false on failure (no match).
*/ */
public function match($requestUrl = null, $requestMethod = null) public function match(string $requestUrl = null, string $requestMethod = null)
{ {
$params = []; $params = [];
// set Request Url if it isn't passed as parameter // set Request Url if it isn't passed as parameter
if ($requestUrl === null) { if ($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; $requestUrl = $_SERVER['REQUEST_URI'] ?? '/';
} }
// strip base path from request url // strip base path from request url
@ -208,7 +206,7 @@ class AltoRouter
// set Request Method if it isn't passed as a parameter // set Request Method if it isn't passed as a parameter
if ($requestMethod === null) { if ($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; $requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
} }
foreach ($this->routes as $handler) { foreach ($this->routes as $handler) {
@ -267,9 +265,9 @@ class AltoRouter
* @param $route * @param $route
* @return string * @return string
*/ */
protected function compileRoute($route) protected function compileRoute($route): string
{ {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes; $matchTypes = $this->matchTypes;
foreach ($matches as $match) { foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match; list($block, $pre, $type, $param, $optional) = $match;

@ -6,7 +6,7 @@ if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) { if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error'); header('HTTP/1.1 500 Internal Server Error');
} }
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; $err = 'Composer 2.3.0 dropped support for auto-loading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) { if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err); fwrite(STDERR, $err);

Loading…
Cancel
Save