src/WebBundle/Controller/PublicationController.php line 48

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