src/Controller/BlogController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Blog\Category;
  4. use App\Entity\Blog\Post;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. class BlogController extends AbstractController
  11. {
  12.     const RESULTS_PER_PAGE 4;
  13.     /**
  14.      * @Route("/lifestyle", name="lifestyle_index")
  15.      * @return Response
  16.      */
  17.     public function index(Request $request)
  18.     {
  19.         $postRepo $this->getDoctrine()->getRepository(Post::class);
  20.         $page abs($request->query->get('page'1));
  21.         $category $request->query->get('category'null);
  22.         $criteria $category ? ['category' => $category] : [];
  23.         $orderBy = ['publishedAt' => 'DESC'];
  24.         $posts $postRepo->findBy($criteria$orderByself::RESULTS_PER_PAGE, ($page 1) * self::RESULTS_PER_PAGE);
  25.         $totalPosts $postRepo->count($criteria);
  26.         $lastPage ceil($totalPosts self::RESULTS_PER_PAGE) ?: 1;
  27.         return $this->render('blog/index.html.twig',[
  28.             'posts' => $posts,
  29.             'categories' => $this->getDoctrine()->getRepository(Category::class)->findAll(),
  30.             'page' => $page,
  31.             'lastPage' => $lastPage
  32.         ]);
  33.     }
  34.     /**
  35.      * @Route("/lifestyle/{id}/{slug}", name="lifestyle_show")
  36.      * @return Response
  37.      */
  38.     public function show(Post $post$slugRequest $request)
  39.     {
  40.         if ($slug !== $post->getSlug()) {
  41.             throw new NotFoundHttpException();
  42.         }
  43.         $category $request->query->get('category'null);
  44.         $criteria $category && $post->getCategory()->getId() === intval($category) ? ['category' => $category] : [];
  45.         $categories  $this->getDoctrine()->getRepository(Category::class)->findAll();
  46.         return $this->render('blog/show.html.twig',[
  47.             'post' => $post,
  48.             'categories' => $categories,
  49.             'nav' => $this->getDoctrine()->getRepository(Post::class)->getPreviousAndNextPost($post$criteria),
  50.         ]);
  51.     }
  52. }