src/WebBundle/Controller/PublicationController.php line 116

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Controller;
  3. use Doctrine\ORM\NonUniqueResultException;
  4. use Exception;
  5. use FlexApp\DTO\Blog\BlogShowData;
  6. use FlexApp\Exceptions\InternalServerErrorException;
  7. use FlexApp\Helper\MetaHelper;
  8. use FlexApp\Service\CalendarService;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  13. use WebBundle\Entity\Publication;
  14. use WebBundle\Entity\PublicationLike;
  15. use WebBundle\Helper\App;
  16. use WebBundle\Helper\LocaleHelper;
  17. use WebBundle\Helper\SearchLogHelper;
  18. use WebBundle\Helper\StrHelper;
  19. use WebBundle\Helper\UrlHelper;
  20. use WebBundle\Helper\UserHelper;
  21. use WebBundle\Repository\PublicationLikeRepository;
  22. use WebBundle\Repository\PublicationRepository;
  23. use WebBundle\Repository\SocialStatRepository;
  24. use WebBundle\Service\PublicationService;
  25. /**
  26.  * Publication controller.
  27.  */
  28. class PublicationController extends ExtendedController
  29. {
  30.     /** @required */
  31.     public PublicationService $publicationService;
  32.     /** @required */
  33.     public CalendarService $calendarService;
  34.     /** @required */
  35.     public PublicationRepository $publicationRepository;
  36.     /**
  37.      * Вывод всех публикаций.
  38.      *
  39.      * @param $action
  40.      *
  41.      * @return Response
  42.      *
  43.      * @throws Exception
  44.      */
  45.     public function indexAction($action null)
  46.     {
  47.         $oTranslator App::getTranslator();
  48.         $param = [
  49.             'hideSingle' => false// проверка, на просмотр только страницы блога
  50.         ];
  51.         if (!$action) {
  52.             $page = [
  53.                 'h1' => $oTranslator->trans('blog_title_all_blogs'),
  54.                 'linkUrl' => $this->generateUrl('app_publications', ['action' => 'top10']),
  55.                 'linkName' => StrHelper::toLower($oTranslator->trans('blog_title_top10_blogs')),
  56.                 'linkTitle' => $oTranslator->trans('blog_title_top10_blogs'),
  57.             ];
  58.         }
  59.         // Решено убрать страницу Топ10, и выводить Все блоги и Топ 10 в рамках одной страницы,
  60.         // поэтому сделан редирект
  61.         /*elseif ($action == 'top10') {
  62.             $param['orderBy'] = 'view DESC'; //Параметр выборки, второй автоматически будет по id
  63.             $param['limit'] = 10; // Параметр количества элементов
  64.             $page = [
  65.                 'h1'        => $oTranslator->trans('blog_title_top10_blogs'),
  66.                 'linkUrl'   => $this->generateUrl('app_publications', ['action' => 'all']),
  67.                 'linkName'  => StrHelper::toLower($oTranslator->trans('blog_title_all_blogs')),
  68.                 'linkTitle' => $oTranslator->trans('blog_title_all_blogs'),
  69.             ];
  70.         }*/
  71.         elseif ('top10' == $action || 'all' == $action) {
  72.             return new RedirectResponse($this->generateUrl('app_publications'), 301);
  73.         } else {
  74.             return new RedirectResponse($this->generateUrl('app_publications')); //default action
  75.         }
  76.         $blogs $this->publicationService->list($param);
  77.         if (!$blogs) {
  78.             throw new NotFoundHttpException('Not found.');
  79.         }
  80.         $metaManager MetaHelper::getManager();
  81.         $response $this->render('@Web/Publication/index.html.twig', [
  82.             'blogs' => $blogs,
  83.             'page' => $page,
  84.             'meta' => [
  85.                 'title' => $metaManager->getTitle(),
  86.                 'description' => $metaManager->getDescription(),
  87.                 'keywords' => $metaManager->getKeywords(),
  88.             ],
  89.         ]);
  90.         SearchLogHelper::save(['url' => App::getRequest()->getUri(), 'title' => $metaManager->getTitle()]);
  91.         return $response;
  92.     }
  93.     /**
  94.      * Показ одной публикации.
  95.      * @param $id
  96.      * @param $preview
  97.      * @return RedirectResponse|Response
  98.      * @throws InternalServerErrorException
  99.      * @throws Exception
  100.      */
  101.     public function showAction($id$preview)
  102.     {
  103.         $locale App::getCurLocale();
  104.         $slug $id;
  105.         // редирект с ID на URL
  106.         // ------------------------------------------------------------------------------
  107.         if (App::isInt($slug)) {
  108.             $blog $this->publicationRepository->findOneBy(['id' => $slug]);
  109.             if (!$blog) {
  110.                 throw new NotFoundHttpException('Not found.');
  111.             }
  112.             $url UrlHelper::genUrlBlogSingle($blog);
  113.             if (!$url) {
  114.                 throw new NotFoundHttpException('Not found.');
  115.             }
  116.             return new RedirectResponse($url301);
  117.         }
  118.         // ------------------------------------------------------------------------------
  119.         $oBlogData = new BlogShowData($slug$preview$locale);
  120.         // если блог не найден, сначала, то проверяем редиректы
  121.         if (!$oBlogData->getData()) {
  122.             if ($newSlug $oBlogData->findNewSlug()) {
  123.                 return new RedirectResponse($oBlogData->getUrl($newSlug), 301);
  124.             }
  125.             throw new NotFoundHttpException('Not found.');
  126.         }
  127.         if ($oBlogData->getSlug() !== $slug) {
  128.             // если смена локали, то проверяем на предмет блогов доставки, что бы редиректы корректно выставить
  129.             if (in_array($oBlogData->getId(), ['2239','2232'])) {
  130.                 // https://te2.remote.team/discus/7D0B4465-82E4-820E-BFF0-F8A245ED8996
  131.                 if (App::getCurCountry() === 'ru') {
  132.                     $newSlug $this->publicationRepository->getKey(2239$locale);
  133.                 } else {
  134.                     $newSlug $this->publicationRepository->getKey(2232$locale);
  135.                 }
  136.                 $newUrl $this->generateUrl('app_publication_single', ['id' => $newSlug]);
  137.             } else {
  138.                 $newUrl $oBlogData->getUrl();
  139.             }
  140.             return new RedirectResponse($newUrl301);
  141.         }
  142.         if (!$oBlogData->isShowSite()) {
  143.             // разрешаем смотреть только админам
  144.             if (!App::isRole('ROLE_ADMIN')) {
  145.                 throw new NotFoundHttpException('Page not found.');
  146.             }
  147.         }
  148.         // редиректим на новый блог экспресс образцов
  149.         if (!$oBlogData->isExhibition() and $oBlogData->getId() == 2214) {
  150.             if ($newUrl $this->publicationRepository->getUrlBlogExpressSamples(true)) {
  151.                 return new RedirectResponse($newUrl302);
  152.             } else {
  153.                 throw new NotFoundHttpException('Page not found.');
  154.             }
  155.         }
  156.         // Обновление статистики просмотров
  157.         $oBlogData->updView();
  158.         $oTrans App::getTranslator();
  159.         $settingsCount = [
  160.             => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%''%count%' => 0], null),
  161.             => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%''%count%' => 1], null),
  162.             => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%''%count%' => 2], null),
  163.             => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%''%count%' => 3], null),
  164.         ];
  165.         $data $oBlogData->getData();
  166.         if (isset($data['body'])) {
  167.             if (!isset($blog) || !$blog) {
  168.                 /** @var Publication $blog */
  169.                 $blog $this->publicationRepository->find($oBlogData->getId());
  170.                 if (!$blog) {
  171.                     throw new InternalServerErrorException("Не нашли в базе блог по id {$oBlogData->getId()}");
  172.                 }
  173.             }
  174.             $this->calendarService->insertHolidays($oBlogData$blog);
  175.         }
  176.         /** @var SocialStatRepository $socialStatRepo */
  177.         $socialStatRepo App::getRepository('WebBundle:SocialStat');
  178.         $social $socialStatRepo->getStatLoginToken($locale);
  179.         $oBlogData->setBody(LocaleHelper::fixLink($oBlogData->getBody()));
  180.         return $this->render('@Web/Publication/show.html.twig', [
  181.             'blog' => $oBlogData,
  182.             'settingsCount' => $settingsCount,
  183.             'social' => $social,
  184.         ]);
  185.     }
  186.     /**
  187.      * Добавление лайка к пибликации.
  188.      *
  189.      * @param $id
  190.      *
  191.      * @return Response
  192.      *
  193.      * @throws NonUniqueResultException
  194.      * @throws Exception
  195.      */
  196.     public function likeAction($id)
  197.     {
  198.         /** @var Publication $publication */
  199.         $publication App::getRepository('WebBundle:Publication')->findOneBy(['id' => $id]);
  200.         $token UserHelper::getInstance()->getToken();
  201.         /** @var PublicationLikeRepository $repoPublicationLike */
  202.         $repoPublicationLike App::getRepository('WebBundle:PublicationLike');
  203.         $publicationLike $repoPublicationLike->getPublicationLike($token$id);
  204.         if (!$publicationLike) {
  205.             /** @var PublicationLike $publicationLike */
  206.             $publicationLike = new PublicationLike();
  207.             $publicationLike->setToken($token);
  208.             $publicationLike->setPublication($publication);
  209.             $em $this->getDoctrine()->getManager();
  210.             $em->persist($publicationLike);
  211.             $em->flush();
  212.             return new JsonResponse(['status' => 1'count' => ($publication->getLikes()->count()), 'token' => $token]);
  213.         } else {
  214.             $publication->getLikes()->removeElement($publicationLike);
  215.             $em $this->getDoctrine()->getManager();
  216.             $em->remove($publicationLike);
  217.             $em->persist($publication);
  218.             $em->flush();
  219.             return new JsonResponse(['status' => 0'count' => ($publication->getLikes()->count()), 'token' => $token]);
  220.         }
  221.     }
  222.     /**
  223.      * Для слайдера.
  224.      *
  225.      * @param int $page
  226.      * @param int $limit
  227.      * @param string $innerBlock
  228.      *
  229.      * @return Response
  230.      */
  231.     public function pageAction($page 1$limit 8$innerBlock '')
  232.     {
  233.         $blogs $this->publicationService
  234.             ->page((int) $page, (int) $limitApp::getCurLocale(), $innerBlock);
  235.         return $this->render('@Web/Publication/page.html.twig', ['blogs' => $blogs]);
  236.     }
  237. }