<?php
namespace App\Controller;
use App\Entity\Article;
use App\Repository\ArticleRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/article")
*/
class ArticleController extends AbstractController
{
/**
* @Route("/{slug}", name="article_show")
*/
public function show(
Article $article,
ArticleRepository $articleRepo,
EntityManagerInterface $em
): Response {
if (!$article->isPublished()) {
throw $this->createNotFoundException('Article non publiƩ');
}
$article->incrementViewCount();
$em->flush();
$relatedArticles = $articleRepo->findPublishedByCategory(
$article->getCategory(),
4
);
$relatedArticles = array_filter($relatedArticles, function($a) use ($article) {
return $a->getId() !== $article->getId();
});
return $this->render('article/show.html.twig', [
'article' => $article,
'related_articles' => array_slice($relatedArticles, 0, 3),
]);
}
/**
* @Route("/preview/{id}", name="article_preview")
*/
public function preview(Article $article): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
return $this->render('article/show.html.twig', [
'article' => $article,
'is_preview' => true,
'related_articles' => [],
]);
}
}