src/Controller/BlogController.php line 49

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\Controller;
  11. use App\Entity\Comment;
  12. use App\Entity\Post;
  13. use App\Event\CommentCreatedEvent;
  14. use App\Form\CommentType;
  15. use App\Repository\PostRepository;
  16. use App\Repository\TagRepository;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  20. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. /**
  27.  * Controller used to manage blog contents in the public part of the site.
  28.  *
  29.  * @author Ryan Weaver <weaverryan@gmail.com>
  30.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  31.  */
  32. #[Route('/blog')]
  33. class BlogController extends AbstractController
  34. {
  35.     /**
  36.      * NOTE: For standard formats, Symfony will also automatically choose the best
  37.      * Content-Type header for the response.
  38.      *
  39.      * See https://symfony.com/doc/current/routing.html#special-parameters
  40.      */
  41.     #[Route('/'defaults: ['page' => '1''_format' => 'html'], methods: ['GET'], name'blog_index')]
  42.     #[Route('/rss.xml'defaults: ['page' => '1''_format' => 'xml'], methods: ['GET'], name'blog_rss')]
  43.     #[Route('/page/{page<[1-9]\d*>}'defaults: ['_format' => 'html'], methods: ['GET'], name'blog_index_paginated')]
  44.     #[Cache(smaxage10)]
  45.     public function index(Request $requestint $pagestring $_formatPostRepository $postsTagRepository $tags): Response
  46.     {
  47.         $tag null;
  48.         if ($request->query->has('tag')) {
  49.             $tag $tags->findOneBy(['name' => $request->query->get('tag')]);
  50.         }
  51.         $latestPosts $posts->findLatest($page$tag);
  52.         // Every template name also has two extensions that specify the format and
  53.         // engine for that template.
  54.         // See https://symfony.com/doc/current/templates.html#template-naming
  55.         return $this->render('blog/index.'.$_format.'.twig', [
  56.             'paginator' => $latestPosts,
  57.             'tagName' => $tag?->getName(),
  58.         ]);
  59.     }
  60.     /**
  61.      * NOTE: The $post controller argument is automatically injected by Symfony
  62.      * after performing a database query looking for a Post with the 'slug'
  63.      * value given in the route.
  64.      *
  65.      * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
  66.      */
  67.     #[Route('/posts/{slug}'methods: ['GET'], name'blog_post')]
  68.     public function postShow(Post $post): Response
  69.     {
  70.         // Symfony's 'dump()' function is an improved version of PHP's 'var_dump()' but
  71.         // it's not available in the 'prod' environment to prevent leaking sensitive information.
  72.         // It can be used both in PHP files and Twig templates, but it requires to
  73.         // have enabled the DebugBundle. Uncomment the following line to see it in action:
  74.         //
  75.         // dump($post, $this->getUser(), new \DateTime());
  76.         //
  77.         // The result will be displayed either in the Symfony Profiler or in the stream output.
  78.         // See https://symfony.com/doc/current/profiler.html
  79.         // See https://symfony.com/doc/current/templates.html#the-dump-twig-utilities
  80.         //
  81.         // You can also leverage Symfony's 'dd()' function that dumps and
  82.         // stops the execution
  83.         return $this->render('blog/post_show.html.twig', ['post' => $post]);
  84.     }
  85.     /**
  86.      * NOTE: The ParamConverter mapping is required because the route parameter
  87.      * (postSlug) doesn't match any of the Doctrine entity properties (slug).
  88.      *
  89.      * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#doctrine-converter
  90.      */
  91.     #[Route('/comment/{postSlug}/new'methods: ['POST'], name'comment_new')]
  92.     #[IsGranted('IS_AUTHENTICATED_FULLY')]
  93.     #[ParamConverter('post'options: ['mapping' => ['postSlug' => 'slug']])]
  94.     public function commentNew(Request $requestPost $postEventDispatcherInterface $eventDispatcherEntityManagerInterface $entityManager): Response
  95.     {
  96.         $comment = new Comment();
  97.         $comment->setAuthor($this->getUser());
  98.         $post->addComment($comment);
  99.         $form $this->createForm(CommentType::class, $comment);
  100.         $form->handleRequest($request);
  101.         if ($form->isSubmitted() && $form->isValid()) {
  102.             $entityManager->persist($comment);
  103.             $entityManager->flush();
  104.             // When an event is dispatched, Symfony notifies it to all the listeners
  105.             // and subscribers registered to it. Listeners can modify the information
  106.             // passed in the event and they can even modify the execution flow, so
  107.             // there's no guarantee that the rest of this controller will be executed.
  108.             // See https://symfony.com/doc/current/components/event_dispatcher.html
  109.             $eventDispatcher->dispatch(new CommentCreatedEvent($comment));
  110.             return $this->redirectToRoute('blog_post', ['slug' => $post->getSlug()]);
  111.         }
  112.         return $this->render('blog/comment_form_error.html.twig', [
  113.             'post' => $post,
  114.             'form' => $form->createView(),
  115.         ]);
  116.     }
  117.     /**
  118.      * This controller is called directly via the render() function in the
  119.      * blog/post_show.html.twig template. That's why it's not needed to define
  120.      * a route name for it.
  121.      *
  122.      * The "id" of the Post is passed in and then turned into a Post object
  123.      * automatically by the ParamConverter.
  124.      */
  125.     public function commentForm(Post $post): Response
  126.     {
  127.         $form $this->createForm(CommentType::class);
  128.         return $this->render('blog/_comment_form.html.twig', [
  129.             'post' => $post,  
  130.             'form' => $form->createView(),
  131.         ]);
  132.     }
  133.     #[Route('/search'methods: ['GET'], name'blog_search')]
  134.     public function search(Request $requestPostRepository $posts): Response
  135.     {
  136.         $query $request->query->get('q''');
  137.         $limit $request->query->get('l'10);
  138.         if (!$request->isXmlHttpRequest()) {
  139.             return $this->render('blog/search.html.twig', ['query' => $query]);
  140.         }
  141.         $foundPosts $posts->findBySearchQuery($query$limit);
  142.         $results = [];
  143.         foreach ($foundPosts as $post) {
  144.             $results[] = [
  145.                 'title' => htmlspecialchars($post->getTitle(), \ENT_COMPAT \ENT_HTML5),
  146.                 'date' => $post->getPublishedAt()->format('M d, Y'),
  147.                 'author' => htmlspecialchars($post->getAuthor()->getFullName(), \ENT_COMPAT \ENT_HTML5),
  148.                 'summary' => htmlspecialchars($post->getSummary(), \ENT_COMPAT \ENT_HTML5),
  149.                 'url' => $this->generateUrl('blog_post', ['slug' => $post->getSlug()]),
  150.             ];
  151.         }
  152.         return $this->json($results);
  153.     }
  154. }