src/Controller/BlogController.php line 61

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Comment;
  4. use App\Entity\Post;
  5. use App\Entity\User;
  6. use App\Form\CommentType;
  7. use App\Repository\BlogRepository;
  8. use App\Repository\PostRepository;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Exception;
  11. use Pagerfanta\Doctrine\ORM\QueryAdapter;
  12. use Pagerfanta\Pagerfanta;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. class BlogController extends AbstractController
  18. {
  19. private ?string $layout;
  20. public const PER_PAGE = 10;
  21. public const RECENT_POSTS_COUNT = 3;
  22. private PostRepository $postRepository;
  23. public function __construct(PostRepository $postRepository)
  24. {
  25. $this->postRepository = $postRepository;
  26. }
  27. /**
  28. * @Route("/blog", name="blog")
  29. *
  30. * @throws Exception
  31. */
  32. public function index(Request $request, BlogRepository $blogRepository, PostRepository $postRepository): Response
  33. {
  34. $this->get_layout($request, $blogRepository);
  35. $queryBuilder = $postRepository->getOrCreateQueryBuilder();
  36. $pagerfanta = new Pagerfanta(new QueryAdapter($queryBuilder));
  37. $pagerfanta->setMaxPerPage(self::PER_PAGE); // for test default value:10
  38. $pagerfanta->setCurrentPage($request->query->get('page', 1));
  39. $categories = $this->getCategoriesFromPost();
  40. $recent = $this->getRecentPosts();
  41. return $this->render('blog/index.html.twig', [
  42. 'controller_name' => 'BlogController',
  43. 'layout' => $this->layout,
  44. 'posts' => $pagerfanta,
  45. 'posts_recent' => $recent,
  46. 'categories' => array_unique($categories),
  47. ]);
  48. }
  49. /**
  50. * @Route("blog/{slug}", name="blog_post")
  51. *
  52. * @throws Exception
  53. */
  54. public function post(Request $request, PostRepository $postRepository, ManagerRegistry $registry): Response
  55. {
  56. $slug = $request->attributes->get('slug');
  57. $post = $this->get_post($slug, $postRepository);
  58. $comment = new Comment();
  59. $form = $this->createForm(CommentType::class, $comment);
  60. $form->handleRequest($request);
  61. $recent = $this->getRecentPosts();
  62. if ($form->isSubmitted() && $form->isValid()) {
  63. $entityManager = $registry->getManager();
  64. /**
  65. * @var User $user
  66. */
  67. $user = $this->getUser();
  68. if (empty($user) || !in_array('ROLE_USER', $user->getRoles())) {
  69. $this->addFlash('error', 'You need to be logged in to comment on this post');
  70. return $this->redirectToRoute('blog_post', [
  71. 'slug' => $slug,
  72. ], Response::HTTP_SEE_OTHER);
  73. }
  74. $comment->setCreatedBy($user);
  75. $comment->setPost($post);
  76. $entityManager->persist($comment);
  77. $entityManager->flush();
  78. return $this->redirectToRoute('blog_post', ['slug' => $slug], Response::HTTP_SEE_OTHER);
  79. }
  80. return $this->render('blog/page.html.twig', [
  81. 'controller_name' => 'BlogController',
  82. 'post' => $this->get_post($slug, $postRepository),
  83. 'form' => $form->createView(),
  84. 'posts_recent' => $recent,
  85. 'categories' => $this->getCategoriesFromPost(),
  86. ] + $this->get_pagination($post, $postRepository));
  87. }
  88. public function get_post($slug, PostRepository $repository): ?Post
  89. {
  90. return $repository
  91. ->findOneBy(['slug' => $slug]);
  92. }
  93. public function get_pagination(Post $post, PostRepository $repository): array
  94. {
  95. $records = $repository->findAll();
  96. $index = array_search($post->getId(), array_reduce($records, function ($memo, $record) {
  97. array_push($memo, $record->getId());
  98. return $memo;
  99. }, []));
  100. return [
  101. 'next' => @$records[($index + 1)] ?: null,
  102. 'prev' => @$records[$index - 1] ?: null,
  103. ];
  104. }
  105. public function get_layout(Request $request, BlogRepository $blogRepository): void
  106. {
  107. $route = $request->attributes->get('_route');
  108. $this->layout = $blogRepository
  109. ->findOneBy(['slug' => $route])
  110. ->getTemplate()
  111. ->getLayout() ?: 'grid';
  112. }
  113. /**
  114. * @throws Exception
  115. */
  116. public function getCategoriesFromPost(): array
  117. {
  118. $categories = [];
  119. foreach ($this->postRepository->findAll() as $post) {
  120. $cat_iterator = $post->getCategories()->getIterator();
  121. foreach ($cat_iterator as $cat) {
  122. $categories[] = $cat;
  123. }
  124. }
  125. return $categories;
  126. }
  127. public function getRecentPosts(): array
  128. {
  129. $posts = [];
  130. foreach (array_reverse($this->postRepository->findAll()) as $index => $post) {
  131. if ($index == self::RECENT_POSTS_COUNT) {
  132. return $posts;
  133. }
  134. $content = $post->getContent();
  135. $block_types = array_column($content, 'type');
  136. $image_index = array_search('image', $block_types);
  137. $posts[] = [
  138. 'image' => $image_index ? $content['blocks'][$image_index] : [
  139. 'data' => [
  140. 'file' => [
  141. 'url' => '',
  142. ],
  143. ],
  144. ],
  145. 'slug' => $post->getSlug(),
  146. 'title' => $post->getTitle(),
  147. 'created_at' => $post->getCreatedAt(),
  148. ];
  149. }
  150. return $posts;
  151. }
  152. }