src/Controller/Admin/BlogController.php line 54

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\Admin;
  11. use App\Entity\Post;
  12. use App\Form\PostType;
  13. use App\Repository\PostRepository;
  14. use App\Security\PostVoter;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. /**
  23.  * Controller used to manage blog contents in the backend.
  24.  *
  25.  * Please note that the application backend is developed manually for learning
  26.  * purposes. However, in your real Symfony application you should use any of the
  27.  * existing bundles that let you generate ready-to-use backends without effort.
  28.  * See https://symfony.com/bundles
  29.  *
  30.  * @author Ryan Weaver <weaverryan@gmail.com>
  31.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  32.  */
  33. #[Route('/admin/post')]
  34. #[IsGranted('ROLE_ADMIN')]
  35. class BlogController extends AbstractController
  36. {
  37.     /**
  38.      * Lists all Post entities.
  39.      *
  40.      * This controller responds to two different routes with the same URL:
  41.      *   * 'admin_post_index' is the route with a name that follows the same
  42.      *     structure as the rest of the controllers of this class.
  43.      *   * 'admin_index' is a nice shortcut to the backend homepage. This allows
  44.      *     to create simpler links in the templates. Moreover, in the future we
  45.      *     could move this annotation to any other controller while maintaining
  46.      *     the route name and therefore, without breaking any existing link.
  47.      */
  48.     #[Route('/'methods: ['GET'], name'admin_index')]
  49.     #[Route('/'methods: ['GET'], name'admin_post_index')]
  50.     public function index(PostRepository $posts): Response
  51.     {
  52.         $authorPosts $posts->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);
  53.         return $this->render('admin/blog/index.html.twig', ['posts' => $authorPosts]);
  54.     }
  55.     /**
  56.      * Creates a new Post entity.
  57.      *
  58.      * NOTE: the Method annotation is optional, but it's a recommended practice
  59.      * to constraint the HTTP methods each controller responds to (by default
  60.      * it responds to all methods).
  61.      */
  62.     #[Route('/new'methods: ['GET''POST'], name'admin_post_new')]
  63.     public function new(Request $requestEntityManagerInterface $entityManager): Response
  64.     {
  65.         $post = new Post();
  66.         $post->setAuthor($this->getUser());
  67.         // See https://symfony.com/doc/current/form/multiple_buttons.html
  68.         $form $this->createForm(PostType::class, $post)
  69.             ->add('saveAndCreateNew'SubmitType::class);
  70.         $form->handleRequest($request);
  71.         // the isSubmitted() method is completely optional because the other
  72.         // isValid() method already checks whether the form is submitted.
  73.         // However, we explicitly add it to improve code readability.
  74.         // See https://symfony.com/doc/current/forms.html#processing-forms
  75.         if ($form->isSubmitted() && $form->isValid()) {
  76.             $entityManager->persist($post);
  77.             $entityManager->flush();
  78.             // Flash messages are used to notify the user about the result of the
  79.             // actions. They are deleted automatically from the session as soon
  80.             // as they are accessed.
  81.             // See https://symfony.com/doc/current/controller.html#flash-messages
  82.             $this->addFlash('success''post.created_successfully');
  83.             if ($form->get('saveAndCreateNew')->isClicked()) {
  84.                 return $this->redirectToRoute('admin_post_new');
  85.             }
  86.             return $this->redirectToRoute('admin_post_index');
  87.         }
  88.         return $this->render('admin/blog/new.html.twig', [
  89.             'post' => $post,
  90.             'form' => $form->createView(),
  91.         ]);
  92.     }
  93.     /**
  94.      * Finds and displays a Post entity.
  95.      */
  96.     #[Route('/{id<\d+>}'methods: ['GET'], name'admin_post_show')]
  97.     public function show(Post $post): Response
  98.     {
  99.         // This security check can also be performed
  100.         // using a PHP attribute: #[IsGranted('show', subject: 'post', message: 'Posts can only be shown to their authors.')]
  101.         $this->denyAccessUnlessGranted(PostVoter::SHOW$post'Posts can only be shown to their authors.');
  102.         return $this->render('admin/blog/show.html.twig', [
  103.             'post' => $post,
  104.         ]);
  105.     }
  106.     /**
  107.      * Displays a form to edit an existing Post entity.
  108.      */
  109.     #[Route('/{id<\d+>}/edit'methods: ['GET''POST'], name'admin_post_edit')]
  110.     #[IsGranted('edit'subject'post'message'Posts can only be edited by their authors.')]
  111.     public function edit(Request $requestPost $postEntityManagerInterface $entityManager): Response
  112.     {
  113.         $form $this->createForm(PostType::class, $post);
  114.         $form->handleRequest($request);
  115.         if ($form->isSubmitted() && $form->isValid()) {
  116.             $entityManager->flush();
  117.             $this->addFlash('success''post.updated_successfully');
  118.             return $this->redirectToRoute('admin_post_edit', ['id' => $post->getId()]);
  119.         }
  120.         return $this->render('admin/blog/edit.html.twig', [
  121.             'post' => $post,
  122.             'form' => $form->createView(),
  123.         ]);
  124.     }
  125.     /**
  126.      * Deletes a Post entity.
  127.      */
  128.     #[Route('/{id}/delete'methods: ['POST'], name'admin_post_delete')]
  129.     #[IsGranted('delete'subject'post')]
  130.     public function delete(Request $requestPost $postEntityManagerInterface $entityManager): Response
  131.     {
  132.         if (!$this->isCsrfTokenValid('delete'$request->request->get('token'))) {
  133.             return $this->redirectToRoute('admin_post_index');
  134.         }
  135.         // Delete the tags associated with this blog post. This is done automatically
  136.         // by Doctrine, except for SQLite (the database used in this application)
  137.         // because foreign key support is not enabled by default in SQLite
  138.         $post->getTags()->clear();
  139.         $entityManager->remove($post);
  140.         $entityManager->flush();
  141.         $this->addFlash('success''post.deleted_successfully');
  142.         return $this->redirectToRoute('admin_post_index');
  143.     }
  144. }