83 lines
2.9 KiB
PHP
83 lines
2.9 KiB
PHP
<?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;
|
|
use Silex\Validation\CommentValidation;
|
|
use Silex\Validation\NewsValidation;
|
|
|
|
class VisitorController {
|
|
|
|
private const PER_PAGE = 12;
|
|
|
|
public function index(DI $di, array $params): HttpResponse
|
|
{
|
|
$errors = [];
|
|
|
|
$gw = $di->getNewsGateway();
|
|
$gwc = $di->getCommentGateway();
|
|
$user = $di->getSecurity()->getCurrentUser();
|
|
|
|
$page = intval($params['page'] ?? 1);
|
|
$total = $gw->getCount();
|
|
|
|
$nbPages = Pagination::getNbPages($total, self::PER_PAGE);
|
|
if(!empty($_GET['dateDeb']) && !empty($_GET['dateFin']) && NewsValidation::isValidDate($_GET,$errors)) {
|
|
$news = $gw->getLike($_GET['dateDeb'], $_GET['dateFin'], $page , self::PER_PAGE);
|
|
} else {
|
|
$news = $gw->getPaginatedRecentNews($page , self::PER_PAGE);
|
|
}
|
|
$nbComments = $gwc->getCommentNumber();
|
|
if ($user !== null) {
|
|
$nbCommentsByUser = $gwc->getCommentNumberFromUser($user->getId());
|
|
} else {
|
|
$nbCommentsByUser = 0;
|
|
}
|
|
return new HttpResponse(200, 'home', ['news' => $news, 'page' => $page, 'nbPages' => $nbPages, 'nbComments' => $nbComments, 'nbCommentsByUser' => $nbCommentsByUser, 'errors' => $errors]);
|
|
}
|
|
|
|
public function viewPost(DI $di, array $params): HttpResponse
|
|
{
|
|
$newsId = intval($params['id']);
|
|
$news = $di->getNewsGateway()->getById($newsId);
|
|
if ($news === null) {
|
|
return new HttpResponse(404, 'errors', ['errors' => ['Unknown news']]);
|
|
}
|
|
if ($news->getSlug() !== $params['slug']) {
|
|
HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect()));
|
|
}
|
|
$comments = $di->getCommentGateway()->getByNewsId($newsId);
|
|
return new HttpResponse(200, 'newsView', ['news' => $news, 'comments' => $comments]);
|
|
}
|
|
|
|
public function comment(DI $di, array $params): HttpResponse
|
|
{
|
|
$newsId = intval($params['id']);
|
|
$news = $di->getNewsGateway()->getById($newsId);
|
|
if ($news === null) {
|
|
return new HttpResponse(404, 'errors', ['errors' => ['Unknown news']]);
|
|
}
|
|
$author = $di->getSecurity()->getCurrentUser();
|
|
$errors = [];
|
|
if (!CommentValidation::isValidComment($_POST, $author === null, $errors)) {
|
|
return new HttpResponse(400, 'errors', ['errors' => $errors]);
|
|
}
|
|
$comment = new Comment(-1, $newsId, new DateTime(), $_POST['content']);
|
|
if ($author !== null) {
|
|
$comment->setAuthor($author);
|
|
} else {
|
|
$_SESSION['previous_name'] = $_POST['name'];
|
|
$comment->setAuthorName($_POST['name']);
|
|
}
|
|
$di->getCommentGateway()->insert($comment);
|
|
HttpResponse::redirect($di->getRouter()->url($news->getSlugRedirect()));
|
|
exit();
|
|
}
|
|
}
|