src/AppBundle/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 AppBundle\Controller;
  11. use AppBundle\Entity\Comment;
  12. use AppBundle\Entity\Post;
  13. use AppBundle\Events;
  14. use AppBundle\Form\CommentType;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  17. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  20. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  21. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  22. use Symfony\Component\EventDispatcher\GenericEvent;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  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 Controller
  35. {
  36.     /**
  37.      * @Route("/", defaults={"page": "1", "_format"="html"}, name="blog_index")
  38.      * @Route("/rss.xml", defaults={"page": "1", "_format"="xml"}, name="blog_rss")
  39.      * @Route("/page/{page}", defaults={"_format"="html"}, requirements={"page": "[1-9]\d*"}, name="blog_index_paginated")
  40.      * @Method("GET")
  41.      * @Cache(smaxage="10")
  42.      *
  43.      * NOTE: For standard formats, Symfony will also automatically choose the best
  44.      * Content-Type header for the response.
  45.      * See https://symfony.com/doc/current/quick_tour/the_controller.html#using-formats
  46.      */
  47.     public function indexAction($page$_format)
  48.     {
  49.         $em $this->getDoctrine()->getManager();
  50.         $posts $em->getRepository(Post::class)->findLatest($page);
  51.         // Every template name also has two extensions that specify the format and
  52.         // engine for that template.
  53.         // See https://symfony.com/doc/current/templating.html#template-suffix
  54.         return $this->render('blog/index.'.$_format.'.twig', ['posts' => $posts]);
  55.     }
  56.     /**
  57.      * @Route("/posts/{slug}", name="blog_post")
  58.      * @Method("GET")
  59.      *
  60.      * NOTE: The $post controller argument is automatically injected by Symfony
  61.      * after performing a database query looking for a Post with the 'slug'
  62.      * value given in the route.
  63.      * See https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
  64.      */
  65.     public function postShowAction(Post $post)
  66.     {
  67.         // Symfony provides a function called 'dump()' which is an improved version
  68.         // of the 'var_dump()' function. It's useful to quickly debug the contents
  69.         // of any variable, but it's not available in the 'prod' environment to
  70.         // prevent any leak of sensitive information.
  71.         // This function can be used both in PHP files and Twig templates. The only
  72.         // requirement is to have enabled the DebugBundle.
  73.         if ('dev' === $this->getParameter('kernel.environment')) {
  74.             dump($post$this->getUser(), new \DateTime());
  75.         }
  76.         return $this->render('blog/post_show.html.twig', ['post' => $post]);
  77.     }
  78.     /**
  79.      * @Route("/comment/{postSlug}/new", name="comment_new")
  80.      * @Method("POST")
  81.      * @Security("is_granted('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 commentNewAction(Request $requestPost $postEventDispatcherInterface $eventDispatcher)
  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.             $em $this->getDoctrine()->getManager();
  97.             $em->persist($comment);
  98.             $em->flush();
  99.             // When triggering an event, you can optionally pass some information.
  100.             // For simple applications, use the GenericEvent object provided by Symfony
  101.             // to pass some PHP variables. For more complex applications, define your
  102.             // own event object classes.
  103.             // See https://symfony.com/doc/current/components/event_dispatcher/generic_event.html
  104.             $event = new GenericEvent($comment);
  105.             // When an event is dispatched, Symfony notifies it to all the listeners
  106.             // and subscribers registered to it. Listeners can modify the information
  107.             // passed in the event and they can even modify the execution flow, so
  108.             // there's no guarantee that the rest of this controller will be executed.
  109.             // See https://symfony.com/doc/current/components/event_dispatcher.html
  110.             $eventDispatcher->dispatch(Events::COMMENT_CREATED$event);
  111.             return $this->redirectToRoute('blog_post', ['slug' => $post->getSlug()]);
  112.         }
  113.         return $this->render('blog/comment_form_error.html.twig', [
  114.             'post' => $post,
  115.             'form' => $form->createView(),
  116.         ]);
  117.     }
  118.     /**
  119.      * This controller is called directly via the render() function in the
  120.      * blog/post_show.html.twig template. That's why it's not needed to define
  121.      * a route name for it.
  122.      *
  123.      * The "id" of the Post is passed in and then turned into a Post object
  124.      * automatically by the ParamConverter.
  125.      *
  126.      * @param Post $post
  127.      *
  128.      * @return Response
  129.      */
  130.     public function commentFormAction(Post $post)
  131.     {
  132.         $form $this->createForm(CommentType::class);
  133.         return $this->render('blog/_comment_form.html.twig', [
  134.             'post' => $post,
  135.             'form' => $form->createView(),
  136.         ]);
  137.     }
  138.     /**
  139.      * @Route("/search", name="blog_search")
  140.      * @Method("GET")
  141.      *
  142.      * @return Response|JsonResponse
  143.      */
  144.     public function searchAction(Request $request)
  145.     {
  146.         if (!$request->isXmlHttpRequest()) {
  147.             return $this->render('blog/search.html.twig');
  148.         }
  149.         $query $request->query->get('q''');
  150.         $posts $this->getDoctrine()->getRepository(Post::class)->findBySearchQuery($query);
  151.         $results = [];
  152.         foreach ($posts as $post) {
  153.             $results[] = [
  154.                 'title' => htmlspecialchars($post->getTitle()),
  155.                 'summary' => htmlspecialchars($post->getSummary()),
  156.                 'url' => $this->generateUrl('blog_post', ['slug' => $post->getSlug()]),
  157.             ];
  158.         }
  159.         return $this->json($results);
  160.     }
  161. }