<?php
namespace App\Controller;
use App\Entity\Blog\Category;
use App\Entity\Blog\Post;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class BlogController extends AbstractController
{
const RESULTS_PER_PAGE = 4;
/**
* @Route("/lifestyle", name="lifestyle_index")
* @return Response
*/
public function index(Request $request)
{
$postRepo = $this->getDoctrine()->getRepository(Post::class);
$page = abs($request->query->get('page', 1));
$category = $request->query->get('category', null);
$criteria = $category ? ['category' => $category] : [];
$orderBy = ['publishedAt' => 'DESC'];
$posts = $postRepo->findBy($criteria, $orderBy, self::RESULTS_PER_PAGE, ($page - 1) * self::RESULTS_PER_PAGE);
$totalPosts = $postRepo->count($criteria);
$lastPage = ceil($totalPosts / self::RESULTS_PER_PAGE) ?: 1;
return $this->render('blog/index.html.twig',[
'posts' => $posts,
'categories' => $this->getDoctrine()->getRepository(Category::class)->findAll(),
'page' => $page,
'lastPage' => $lastPage
]);
}
/**
* @Route("/lifestyle/{id}/{slug}", name="lifestyle_show")
* @return Response
*/
public function show(Post $post, $slug, Request $request)
{
if ($slug !== $post->getSlug()) {
throw new NotFoundHttpException();
}
$category = $request->query->get('category', null);
$criteria = $category && $post->getCategory()->getId() === intval($category) ? ['category' => $category] : [];
$categories = $this->getDoctrine()->getRepository(Category::class)->findAll();
return $this->render('blog/show.html.twig',[
'post' => $post,
'categories' => $categories,
'nav' => $this->getDoctrine()->getRepository(Post::class)->getPreviousAndNextPost($post, $criteria),
]);
}
}