src/Controller/BlogController.php line 50

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