Permet de poster un commentaire sans être connecté

This commit is contained in:
2022-12-11 12:04:47 +01:00
parent 7596d26652
commit c2412de95a
8 changed files with 88 additions and 75 deletions

View File

@@ -10,14 +10,12 @@ $loader->register();
$security = new \Silex\Controller\SecurityController(); $security = new \Silex\Controller\SecurityController();
$visitor = new \Silex\Controller\VisitorController(); $visitor = new \Silex\Controller\VisitorController();
$user = new \Silex\Controller\UserController();
$admin = new \Silex\Controller\AdminController(); $admin = new \Silex\Controller\AdminController();
$router = new Router($_SERVER['REQUEST_URI']); $router = new Router($_SERVER['REQUEST_URI']);
$router->setBasePath("~cofrizot/silex/index.php");
$router->get('/^$/', [$visitor, 'index']); $router->get('/^$/', [$visitor, 'index']);
$router->get('/^recent\/(?<page>\d+)$/', [$visitor, 'index']); $router->get('/^recent\/(?<page>\d+)$/', [$visitor, 'index']);
$router->get('/^news\/(?<slug>[A-Za-z0-9-]+)-(?<id>\d+)$/', [$visitor, 'viewPost']); $router->get('/^news\/(?<slug>[A-Za-z0-9-]+)-(?<id>\d+)$/', [$visitor, 'viewPost']);
$router->post('/^comment\/(?<id>\d+)$/', [$user, 'comment']); $router->post('/^comment\/(?<id>\d+)$/', [$visitor, 'comment']);
$router->match('/^login$/', [$security, 'login']); $router->match('/^login$/', [$security, 'login']);
$router->match('/^register$/', [$security, 'register']); $router->match('/^register$/', [$security, 'register']);
$router->match('/^logout$/', [$security, 'logout']); $router->match('/^logout$/', [$security, 'logout']);

View File

@@ -23,13 +23,6 @@ class FrontController
&& ($di->getSecurity()->getCurrentUser() === null || !$di->getSecurity()->getCurrentUser()->isAdmin())) { && ($di->getSecurity()->getCurrentUser() === null || !$di->getSecurity()->getCurrentUser()->isAdmin())) {
HttpResponse::redirect($di->getRouter()->url('login')); HttpResponse::redirect($di->getRouter()->url('login'));
} }
if($this->route->getController() instanceof UserController
&& $di->getSecurity()->getCurrentUser() === null)
{
HttpResponse::redirect($di->getRouter()->url('login'));
}
return $this->route->call($di); return $this->route->call($di);
} }
} }

View File

@@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace Silex\Controller;
use DateTime;
use Silex\DI\DI;
use Silex\Http\HttpResponse;
use Silex\Model\Comment;
use Silex\Util\Pagination;
class UserController
{
private const PER_PAGE = 12;
public function comment(DI $di, array $params): void
{
$newsId = intval($params['id']);
$news = $di->getNewsGateway()->getById($newsId);
$di->getCommentGateway()->insert(new Comment(-1, $newsId, new DateTime(), $_POST['content'], $di->getSecurity()->getCurrentUserId()));
HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect()));
}
}

View File

@@ -4,8 +4,10 @@ declare(strict_types=1);
namespace Silex\Controller; namespace Silex\Controller;
use DateTime;
use Silex\DI\DI; use Silex\DI\DI;
use Silex\Http\HttpResponse; use Silex\Http\HttpResponse;
use Silex\Model\Comment;
use Silex\Util\Pagination; use Silex\Util\Pagination;
class VisitorController { class VisitorController {
@@ -23,7 +25,7 @@ class VisitorController {
$nbPages = Pagination::getNbPages($total, self::PER_PAGE); $nbPages = Pagination::getNbPages($total, self::PER_PAGE);
$news = $gw->getPaginatedRecentNews($page , self::PER_PAGE); $news = $gw->getPaginatedRecentNews($page , self::PER_PAGE);
$nbComments = $gwc->getCommentNumber(); $nbComments = $gwc->getCommentNumber();
if($user !== null){ if ($user !== null) {
$nbCommentsByUser = $gwc->getCommentNumberFromUser($user->getId()); $nbCommentsByUser = $gwc->getCommentNumberFromUser($user->getId());
} else { } else {
$nbCommentsByUser = 0; $nbCommentsByUser = 0;
@@ -35,10 +37,25 @@ class VisitorController {
{ {
$newsId = intval($params['id']); $newsId = intval($params['id']);
$news = $di->getNewsGateway()->getById($newsId); $news = $di->getNewsGateway()->getById($newsId);
if($news->getSlug() !== $params['slug']){ if ($news->getSlug() !== $params['slug']) {
HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect())); HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect()));
} }
$comments = $di->getCommentGateway()->getByNewsId($newsId); $comments = $di->getCommentGateway()->getByNewsId($newsId);
return new HttpResponse(200, 'newsView', ['news' => $news, 'comments' => $comments]); return new HttpResponse(200, 'newsView', ['news' => $news, 'comments' => $comments]);
} }
public function comment(DI $di, array $params): void
{
$newsId = intval($params['id']);
$news = $di->getNewsGateway()->getById($newsId);
$comment = new Comment(-1, $newsId, new DateTime(), $_POST['content']);
$author = $di->getSecurity()->getCurrentUser();
if ($author !== null) {
$comment->setAuthor($author);
} else {
$comment->setAuthorName($_POST['name']);
}
$di->getCommentGateway()->insert($comment);
HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect()));
}
} }

View File

@@ -19,8 +19,16 @@ class CommentGateway
public function insert(Comment $comment): bool public function insert(Comment $comment): bool
{ {
$req = $this->pdo->prepare('INSERT INTO comment (news_id, content, author_id) VALUES (:news_id, :content, :author_id);'); $req = $this->pdo->prepare('INSERT INTO comment (news_id, content, author_id, author_name) VALUES (:news_id, :content, :author_id, :author_name);');
$req->execute(['news_id' => $comment->getNewsId(), 'content' => $comment->getContent(), 'author_id' => $comment->getAuthorId()]); $req->bindValue(':news_id', $comment->getNewsId(), PDO::PARAM_INT);
$req->bindValue(':content', $comment->getContent());
$req->bindValue(':author_id', $comment->getAuthorId(), $comment->getAuthorId() !== null ? PDO::PARAM_INT : PDO::PARAM_NULL);
if ($comment->getAuthorId() === null) {
$req->bindValue(':author_name', $comment->getAuthorName());
} else {
$req->bindValue(':author_name', null, PDO::PARAM_NULL);
}
$req->execute();
$comment->setId(intval($this->pdo->lastInsertId())); $comment->setId(intval($this->pdo->lastInsertId()));
return true; return true;
} }
@@ -43,7 +51,7 @@ class CommentGateway
*/ */
public function getByNewsId(int $id): array public function getByNewsId(int $id): array
{ {
$req = $this->pdo->prepare('SELECT c.*, u.login author_login FROM comment c INNER JOIN registered_user u ON u.id_user = c.author_id WHERE c.news_id = :id ORDER BY c.publication_date ASC'); $req = $this->pdo->prepare('SELECT c.*, COALESCE(c.author_name, u.login) author_name FROM comment c LEFT JOIN registered_user u ON u.id_user = c.author_id WHERE c.news_id = :id ORDER BY c.publication_date ASC');
$req->bindValue(':id', $id, PDO::PARAM_INT); $req->bindValue(':id', $id, PDO::PARAM_INT);
if (!$req->execute()) { if (!$req->execute()) {
return []; return [];
@@ -60,8 +68,7 @@ class CommentGateway
$req = $this->pdo->prepare('SELECT COUNT(*) FROM comment'); $req = $this->pdo->prepare('SELECT COUNT(*) FROM comment');
$req->execute(); $req->execute();
$data = $req->fetch(); $data = $req->fetch();
$nbComment = intval($data[0]); return intval($data[0]);
return $nbComment;
} }
public function getCommentNumberFromUser(int $id): int public function getCommentNumberFromUser(int $id): int
@@ -70,8 +77,7 @@ class CommentGateway
$req->bindValue(':id', $id, PDO::PARAM_INT); $req->bindValue(':id', $id, PDO::PARAM_INT);
$req->execute(); $req->execute();
$data = $req->fetch(); $data = $req->fetch();
$nbComment = intval($data[0]); return intval($data[0]);
return $nbComment;
} }
private function createComment(array $data): Comment private function createComment(array $data): Comment
@@ -83,8 +89,8 @@ class CommentGateway
$data['content'], $data['content'],
intval($data['author_id']) intval($data['author_id'])
); );
if (isset($data['author_login'])) { if (isset($data['author_name'])) {
$comment->setAuthorLogin($data['author_login']); $comment->setAuthorName($data['author_name']);
} }
return $comment; return $comment;
} }

View File

@@ -12,16 +12,15 @@ class Comment
private int $newsId; private int $newsId;
private DateTime $publicationDate; private DateTime $publicationDate;
private string $content; private string $content;
private int $authorId; private ?int $authorId = null;
private string $authorLogin; private string $authorName;
public function __construct(int $idComment, int $newsId, DateTime $publicationDate, string $content, int $authorId) public function __construct(int $idComment, int $newsId, DateTime $publicationDate, string $content)
{ {
$this->idComment = $idComment; $this->idComment = $idComment;
$this->newsId = $newsId; $this->newsId = $newsId;
$this->publicationDate = $publicationDate; $this->publicationDate = $publicationDate;
$this->content = $content; $this->content = $content;
$this->authorId = $authorId;
} }
public function getId(): int public function getId(): int
@@ -44,14 +43,14 @@ class Comment
return $this->content; return $this->content;
} }
public function getAuthorId(): int public function getAuthorId(): ?int
{ {
return $this->authorId; return $this->authorId;
} }
public function getAuthorLogin(): string public function getAuthorName(): string
{ {
return $this->authorLogin; return $this->authorName;
} }
public function setId(int $id): void public function setId(int $id): void
@@ -59,8 +58,14 @@ class Comment
$this->idComment = $id; $this->idComment = $id;
} }
public function setAuthorLogin(string $authorLogin): void public function setAuthorName(string $authorName): void
{ {
$this->authorLogin = $authorLogin; $this->authorName = $authorName;
}
public function setAuthor(User $author): void
{
$this->authorId = $author->getId();
$this->authorName = $author->getLogin();
} }
} }

View File

@@ -20,7 +20,9 @@ CREATE TABLE comment (
news_id INT NOT NULL, news_id INT NOT NULL,
publication_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, publication_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
content TEXT NOT NULL, content TEXT NOT NULL,
author_id INT NOT NULL, author_id INT NULL,
author_name VARCHAR(32) NULL,
CONSTRAINT either_authors CHECK ((author_id IS NULL) != (author_name IS NULL)),
FOREIGN KEY (news_id) REFERENCES news(id_news) FOREIGN KEY (news_id) REFERENCES news(id_news)
ON DELETE CASCADE, ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES registered_user(id_user) FOREIGN KEY (author_id) REFERENCES registered_user(id_user)

View File

@@ -1,31 +1,48 @@
<?php $title = $params['news']->getTitle(); ?> <?php
/**
* @var \Silex\Model\News $news
*/
$news = $params['news'];
/**
* @var \Silex\Model\Comment[] $comments
*/
$comments = $params['comments'];
$title = $news->getTitle();
?>
<h1>News</h1> <h1>News</h1>
<div class="card"> <div class="card">
<header class="card-header"> <header class="card-header">
<p class="card-header-title"> <p class="card-header-title">
<?= $params['news']->getTitle() ?> <?= $news->getTitle() ?>
</p> </p>
</header> </header>
<div class="card-content"> <div class="card-content">
<div class="content"> <div class="content">
<?= $params['news']->getContent() ?> <?= $news->getContent() ?>
</div> </div>
</div> </div>
</div> </div>
<section class="section comments"> <section class="section comments">
<?php foreach ($params['comments'] as $comment) : ?> <?php foreach ($comments as $comment) : ?>
<article class="message"> <article class="message">
<header class="message-header"> <header class="message-header">
From <?= $comment->getAuthorLogin() ?> published on <?= $comment->getPublicationDate()->format('Y-m-d H:i:s') ?> From <?= $comment->getAuthorName() ?> published on <?= $comment->getPublicationDate()->format('Y-m-d H:i:s') ?>
</header> </header>
<div class="message-body"> <div class="message-body">
<?= $comment->getContent() ?> <?= $comment->getContent() ?>
</div> </div>
</article> </article>
<?php endforeach; ?> <?php endforeach; ?>
<?php if ($security->getCurrentUserId() !== null) : ?>
<form action="<?= $router->url('comment/' . $params['news']->getId()) ?>" method="post"> <form action="<?= $router->url('comment/' . $params['news']->getId()) ?>" method="post">
<?php if ($security->getCurrentUserId() === null): ?>
<div class="field">
<label class="label" for="name">Name</label>
<div class="control">
<input class="input" id="name" name="name">
</div>
</div>
<?php endif; ?>
<div class="field"> <div class="field">
<label class="label" for="content">Comment</label> <label class="label" for="content">Comment</label>
<div class="control"> <div class="control">
@@ -39,5 +56,4 @@
</div> </div>
</div> </div>
</form> </form>
<?php endif; ?>
</section> </section>