src/Controller/BlogController.php line 51

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.     #[
  42.         Route('/'defaults: ['page' => '1''_format' => 'html'], methods: ['GET'], name'blog_index'),
  43.         Route('/rss.xml'defaults: ['page' => '1''_format' => 'xml'], methods: ['GET'], name'blog_rss'),
  44.         Route('/page/{page<[1-9]\d*>}'defaults: ['_format' => 'html'], methods: ['GET'], name'blog_index_paginated'),
  45.     ]
  46.     #[Cache(smaxage10)]
  47.     public function index(Request $requestint $pagestring $_formatPostRepository $postsTagRepository $tags): Response
  48.     {
  49.         $tag null;
  50.         if ($request->query->has('tag')) {
  51.             $tag $tags->findOneBy(['name' => $request->query->get('tag')]);
  52.         }
  53.         $latestPosts $posts->findLatest($page$tag);
  54.         // Every template name also has two extensions that specify the format and
  55.         // engine for that template.
  56.         // See https://symfony.com/doc/current/templates.html#template-naming
  57.         return $this->render('blog/index.'.$_format.'.twig', [
  58.             'paginator' => $latestPosts,
  59.             'tagName' => $tag $tag->getName() : null,
  60.         ]);
  61.     }
  62.     /**
  63.      * NOTE: The $post controller argument is automatically injected by Symfony
  64.      * after performing a database query looking for a Post with the 'slug'
  65.      * value given in the route.
  66.      *
  67.      * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
  68.      */
  69.     #[Route('/posts/{slug}'methods: ['GET'], name'blog_post')]
  70.     public function postShow(Post $post): Response
  71.     {
  72.         // Symfony's 'dump()' function is an improved version of PHP's 'var_dump()' but
  73.         // it's not available in the 'prod' environment to prevent leaking sensitive information.
  74.         // It can be used both in PHP files and Twig templates, but it requires to
  75.         // have enabled the DebugBundle. Uncomment the following line to see it in action:
  76.         //
  77.         // dump($post, $this->getUser(), new \DateTime());
  78.         //
  79.         // The result will be displayed either in the Symfony Profiler or in the stream output.
  80.         // See https://symfony.com/doc/current/profiler.html
  81.         // See https://symfony.com/doc/current/templates.html#the-dump-twig-utilities
  82.         //
  83.         // You can also leverage Symfony's 'dd()' function that dumps and
  84.         // stops the execution
  85.         return $this->render('blog/post_show.html.twig', ['post' => $post]);
  86.     }
  87.     /**
  88.      * NOTE: The ParamConverter mapping is required because the route parameter
  89.      * (postSlug) doesn't match any of the Doctrine entity properties (slug).
  90.      *
  91.      * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#doctrine-converter
  92.      */
  93.     #[Route('/comment/{postSlug}/new'methods: ['POST'], name'comment_new')]
  94.     #[IsGranted('IS_AUTHENTICATED_FULLY')]
  95.     #[ParamConverter('post'options: ['mapping' => ['postSlug' => 'slug']])]
  96.     public function commentNew(Request $requestPost $postEventDispatcherInterface $eventDispatcherEntityManagerInterface $entityManager): Response
  97.     {
  98.         $comment = new Comment();
  99.         $comment->setAuthor($this->getUser());
  100.         $post->addComment($comment);
  101.         $form $this->createForm(CommentType::class, $comment);
  102.         $form->handleRequest($request);
  103.         if ($form->isSubmitted() && $form->isValid()) {
  104.             $entityManager->persist($comment);
  105.             $entityManager->flush();
  106.             // When an event is dispatched, Symfony notifies it to all the listeners
  107.             // and subscribers registered to it. Listeners can modify the information
  108.             // passed in the event and they can even modify the execution flow, so
  109.             // there's no guarantee that the rest of this controller will be executed.
  110.             // See https://symfony.com/doc/current/components/event_dispatcher.html
  111.             $eventDispatcher->dispatch(new CommentCreatedEvent($comment));
  112.             return $this->redirectToRoute('blog_post', ['slug' => $post->getSlug()]);
  113.         }
  114.         return $this->render('blog/comment_form_error.html.twig', [
  115.             'post' => $post,
  116.             'form' => $form->createView(),
  117.         ]);
  118.     }
  119.     /**
  120.      * This controller is called directly via the render() function in the
  121.      * blog/post_show.html.twig template. That's why it's not needed to define
  122.      * a route name for it.
  123.      *
  124.      * The "id" of the Post is passed in and then turned into a Post object
  125.      * automatically by the ParamConverter.
  126.      */
  127.     public function commentForm(Post $post): Response
  128.     {
  129.         $form $this->createForm(CommentType::class);
  130.         return $this->render('blog/_comment_form.html.twig', [
  131.             'post' => $post,
  132.             'form' => $form->createView(),
  133.         ]);
  134.     }
  135.     #[Route('/search'methods: ['GET'], name'blog_search')]
  136.     public function search(Request $requestPostRepository $posts): Response
  137.     {
  138.         $query $request->query->get('q''');
  139.         $limit $request->query->get('l'10);
  140.         if (!$request->isXmlHttpRequest()) {
  141.             return $this->render('blog/search.html.twig', ['query' => $query]);
  142.         }
  143.         $foundPosts $posts->findBySearchQuery($query$limit);
  144.         $results = [];
  145.         foreach ($foundPosts as $post) {
  146.             $results[] = [
  147.                 'title' => htmlspecialchars($post->getTitle(), \ENT_COMPAT \ENT_HTML5),
  148.                 'date' => $post->getPublishedAt()->format('M d, Y'),
  149.                 'author' => htmlspecialchars($post->getAuthor()->getFullName(), \ENT_COMPAT \ENT_HTML5),
  150.                 'summary' => htmlspecialchars($post->getSummary(), \ENT_COMPAT \ENT_HTML5),
  151.                 'url' => $this->generateUrl('blog_post', ['slug' => $post->getSlug()]),
  152.             ];
  153.         }
  154.         return $this->json($results);
  155.     }
  156. }