wip FrontController
continuous-integration/drone/push Build is passing Details

pull/17/head
DahmaneYanis 1 year ago
parent 3422ef8780
commit 61a6b5afd5

@ -35,7 +35,7 @@ class ViewHttpResponse extends HttpResponse {
- arguments: array
- kind: int
+ __construct(kind: int, file: string, arguments: array, code: int = HttpCodes::OK)
- __construct(kind: int, file: string, arguments: array, code: int = HttpCodes::OK)
+ getViewKind(): int
+ getFile(): string
+ getArguments(): array

@ -4,6 +4,7 @@ require "../vendor/autoload.php";
require "../config.php";
require "../sql/database.php";
require "utils.php";
require "../src/react-display.php";
use App\Connexion;
@ -19,18 +20,17 @@ use Twig\Loader\FilesystemLoader;
use App\Validation\ValidationFail;
use App\Controller\ErrorController;
session_start();
$basePath = get_public_path();
var_dump($basePath);
$con = new Connexion(get_database());
// routes initialization
$router = new AltoRouter();
$router->setBasePath($basePath);
$frontController = new FrontController($router);
$frontController->route();
//$sampleFormController = new SampleFormController(new FormResultGateway($con), $twig);
//$editorController = new EditorController(new TacticModel(new TacticInfoGateway($con)));
global $dictActionRole;
$dictActionRole = [
"UserController" => "public",
"EditionUserController" => "editor"
];
$frontController = new FrontController($con, $basePath, $dictActionRole);
$frontController->run();

@ -3,13 +3,18 @@
namespace App\Controller;
use App\Connexion;
use App\Controller\UserController;
use AltoRouter;
use App\Controller\ErrorController;
use App\Gateway\FormResultGateway;
use App\Gateway\TacticInfoGateway;
use App\Http\HttpCodes;
use App\Http\HttpResponse;
use App\Http\JsonHttpResponse;
use App\Http\ViewHttpResponse;
use App\Model\TacticModel;
use App\Validation\ValidationFail;
use Twig\Loader\FilesystemLoader;
@ -17,44 +22,110 @@ use Twig\Loader\FilesystemLoader;
class FrontController{
private AltoRouter $router;
private ?UserController $userController;
private Connexion $con;
private array $dictControllerRole;
public function __construct(Connexion $con, string $basePath, array $dictControllerRole) {
$this->con = $con;
$this->router = $this->createRouter($basePath);
$this->dictControllerRole = $dictControllerRole;
}
/**
* Main behavior of the FrontController
*
* @return void
*/
public function run() : void {
$this->initializeRouterMap();
public function __construct(AltoRouter $router){
$this->router = $router;
$this->userController = new UserController();
$match = $this->router->match();
if ($this->validMatch($match)){
$this->roleControl($match['target']);
} else {
$this->displayByViewKind(ViewHttpResponse::twig("error.html.twig", [], HttpCodes::NOT_FOUND));
}
// $this->roleControl($match["target"]);
// $this->handleByResponseType($this->matchRoute());
}
public function run() {
$this->route();
/**
* Create a new instance of an AltoRouter
*
* @param string $basePath
* @return AltoRouter
*/
public function createRouter(string $basePath) : AltoRouter {
$router = new AltoRouter();
$router->setBasePath($basePath);
return $router;
}
public function route()
{
$this->router->map("GET", "/", fn() => $this->userController->home());
// $router->map("GET", "/", fn() => $sampleFormController->displayFormReact());
// $router->map("POST", "/submit", fn() => $sampleFormController->submitFormReact($_POST));
// $router->map("GET", "/twig", fn() => $sampleFormController->displayFormTwig());
// $router->map("POST", "/submit-twig", fn() => $sampleFormController->submitFormTwig($_POST));
// $router->map("GET", "/tactic/new", fn() => $editorController->makeNew());
// $router->map("GET", "/tactic/[i:id]/edit", fn(int $id) => $editorController->openEditorFor($id));
/**
* Initialize project's routes
*
* @return void
*/
private function initializeRouterMap() : void {
$this->router->map("GET", "/", "UserController");
$this->router->map("GET", "/[a:action]?", "UserController");
$this->router->map("GET", "/tactic/[a:action]/[i:idTactic]?", "EditorController");
// $this->router->map("GET", "/tactic/[i:id]/edit", "EditorController");
// $this->router->map("GET", "/", fn() => (new UserController())->home());
// $this->router->map("GET", "/tactic/new", fn() => (new EditorController(new TacticModel(new TacticInfoGateway($this->con))))->makeNew());
// $this->router->map("GET", "/tactic/[i:id]/edit", fn(int $id) => (new EditorController(new TacticModel(new TacticInfoGateway($this->con))))->openEditorFor($id));
}
$match = $this->router->match();
private function validMatch($match){
return $match != null;
}
if ($match == null) {
$loader = new FilesystemLoader('../src/Views/');
$twig = new \Twig\Environment($loader);
http_response_code(HttpCodes::NOT_FOUND);
ErrorController::displayFailures([ValidationFail::notFound("Cette page n'existe pas")], $twig);
return;
/**
* Initialize router's settings
*
* @return ViewHttpResponse
*/
private function roleControl(string $actionController){
if (isset($_SESSION['role'])){
if($_SESSION['role'] = $this->dictControllerRole[$actionController]){
echo "Là on redirige vers le bon controller";
}
}
$this->handleByResponseType($match);
else {
$_SESSION['role']
echo "session initialisé";
}
private function handleByResponseType(array $match)
{
$response = call_user_func_array($match['target'], $match['params']);
// // Page not found
// if ($match == null) {
// return new ViewHttpResponse(ViewHttpResponse::TWIG_VIEW, "Views/error.html.twig", [ValidationFail::notFound("Cette page n'existe pas")], HttpCodes::NOT_FOUND);
// }
// // $loader = new FilesystemLoader('../src/Views/');
// // $twig = new \Twig\Environment($loader);
// // http_response_code(HttpCodes::NOT_FOUND);
// // ErrorController::displayFailures([ValidationFail::notFound("Cette page n'existe pas")], $twig);
// // return;
// // }
}
/**
* Redirect the return of the response by the response's type
*
* @param array $match
* @return void
*/
private function handleByResponseType(HttpResponse $response) : void {
// $response = call_user_func_array($match['target'], $match['params']);
http_response_code($response->getCode());
if ($response instanceof ViewHttpResponse) {
@ -66,7 +137,13 @@ class FrontController{
}
}
private function displayByViewKind(ViewHttpResponse $response){
/**
* Use the right method to display the response
*
* @param ViewHttpResponse $response
* @return void
*/
private function displayByViewKind(ViewHttpResponse $response) : void {
$file = $response->getFile();
$args = $response->getArguments();
@ -82,11 +159,9 @@ class FrontController{
} catch (\Twig\Error\RuntimeError | \Twig\Error\SyntaxError $e) {
http_response_code(500);
echo "There was an error rendering your view, please refer to an administrator.\nlogs date: " . date("YYYD, d M Y H:i:s");
throw e;
throw $e;
}
break;
}
}
}

@ -1,52 +0,0 @@
<?php
namespace App\Controller;
require_once __DIR__ . "/../react-display.php";
use App\Gateway\FormResultGateway;
use App\Http\HttpRequest;
use App\Http\HttpResponse;
use App\Http\ViewHttpResponse;
use App\Validation\Validators;
class SampleFormController {
private FormResultGateway $gateway;
/**
* @param FormResultGateway $gateway
*/
public function __construct(FormResultGateway $gateway) {
$this->gateway = $gateway;
}
public function displayFormReact(): HttpResponse {
return ViewHttpResponse::react("views/SampleForm.tsx", []);
}
public function displayFormTwig(): HttpResponse {
return ViewHttpResponse::twig('sample_form.html.twig', []);
}
private function submitForm(array $form, callable $response): HttpResponse {
return Control::runCheckedFrom($form, [
"name" => [Validators::lenBetween(0, 32), Validators::name("Le nom ne peut contenir que des lettres, des chiffres et des accents")],
"description" => [Validators::lenBetween(0, 512)]
], function (HttpRequest $req) use ($response) {
$description = htmlspecialchars($req["description"]);
$this->gateway->insert($req["name"], $description);
$results = ["results" => $this->gateway->listResults()];
return call_user_func_array($response, [$results]);
}, false);
}
public function submitFormTwig(array $form): HttpResponse {
return $this->submitForm($form, fn(array $results) => ViewHttpResponse::twig('display_results.html.twig', $results));
}
public function submitFormReact(array $form): HttpResponse {
return $this->submitForm($form, fn(array $results) => ViewHttpResponse::react('views/DisplayResults.tsx', $results));
}
}

@ -1,33 +0,0 @@
<?php
namespace App\Gateway;
use PDO;
use App\Connexion;
/**
* A sample gateway, that stores the sample form's result.
*/
class FormResultGateway {
private Connexion $con;
public function __construct(Connexion $con) {
$this->con = $con;
}
function insert(string $username, string $description) {
$this->con->exec(
"INSERT INTO FormEntries VALUES (:name, :description)",
[
":name" => [$username, PDO::PARAM_STR],
"description" => [$description, PDO::PARAM_STR]
]
);
}
function listResults(): array {
return $this->con->fetch("SELECT * FROM FormEntries", []);
}
}

@ -8,6 +8,6 @@
<title>Document</title>
</head>
<body>
<h1>Test</h1>
<h1>Page Home à faire</h1>
</body>
</html>

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Twig view</title>
</head>
<body>
<h1>Hello, this is a sample form made in Twig !</h1>
<form action="submit-twig" method="POST">
<label for="name">your name: </label>
<input type="text" id="name" name="name"/>
<label for="password">a little description about yourself: </label>
<input type="text" id="password" name="description"/>
<input type="submit" value="click me to submit!"/>
</form>
</body>
</html>
Loading…
Cancel
Save