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