<?php
namespace WebBundle\Controller;
use Doctrine\ORM\NonUniqueResultException;
use Exception;
use FlexApp\DTO\Blog\BlogShowData;
use FlexApp\Exceptions\InternalServerErrorException;
use FlexApp\Helper\MetaHelper;
use FlexApp\Service\CalendarService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use WebBundle\Entity\Publication;
use WebBundle\Entity\PublicationLike;
use WebBundle\Helper\App;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\SearchLogHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Helper\UrlHelper;
use WebBundle\Helper\UserHelper;
use WebBundle\Repository\PublicationLikeRepository;
use WebBundle\Repository\PublicationRepository;
use WebBundle\Repository\SocialStatRepository;
use WebBundle\Service\PublicationService;
/**
* Publication controller.
*/
class PublicationController extends ExtendedController
{
/** @required */
public PublicationService $publicationService;
/** @required */
public CalendarService $calendarService;
/** @required */
public PublicationRepository $publicationRepository;
/**
* Вывод всех публикаций.
*
* @param $action
*
* @return Response
*
* @throws Exception
*/
public function indexAction($action = null)
{
$oTranslator = App::getTranslator();
$param = [
'hideSingle' => false, // проверка, на просмотр только страницы блога
];
if (!$action) {
$page = [
'h1' => $oTranslator->trans('blog_title_all_blogs'),
'linkUrl' => $this->generateUrl('app_publications', ['action' => 'top10']),
'linkName' => StrHelper::toLower($oTranslator->trans('blog_title_top10_blogs')),
'linkTitle' => $oTranslator->trans('blog_title_top10_blogs'),
];
}
// Решено убрать страницу Топ10, и выводить Все блоги и Топ 10 в рамках одной страницы,
// поэтому сделан редирект
/*elseif ($action == 'top10') {
$param['orderBy'] = 'view DESC'; //Параметр выборки, второй автоматически будет по id
$param['limit'] = 10; // Параметр количества элементов
$page = [
'h1' => $oTranslator->trans('blog_title_top10_blogs'),
'linkUrl' => $this->generateUrl('app_publications', ['action' => 'all']),
'linkName' => StrHelper::toLower($oTranslator->trans('blog_title_all_blogs')),
'linkTitle' => $oTranslator->trans('blog_title_all_blogs'),
];
}*/
elseif ('top10' == $action || 'all' == $action) {
return new RedirectResponse($this->generateUrl('app_publications'), 301);
} else {
return new RedirectResponse($this->generateUrl('app_publications')); //default action
}
$blogs = $this->publicationService->list($param);
if (!$blogs) {
throw new NotFoundHttpException('Not found.');
}
$metaManager = MetaHelper::getManager();
$response = $this->render('@Web/Publication/index.html.twig', [
'blogs' => $blogs,
'page' => $page,
'meta' => [
'title' => $metaManager->getTitle(),
'description' => $metaManager->getDescription(),
'keywords' => $metaManager->getKeywords(),
],
]);
SearchLogHelper::save(['url' => App::getRequest()->getUri(), 'title' => $metaManager->getTitle()]);
return $response;
}
/**
* Показ одной публикации.
* @param $id
* @param $preview
* @return RedirectResponse|Response
* @throws InternalServerErrorException
* @throws Exception
*/
public function showAction($id, $preview)
{
$locale = App::getCurLocale();
$slug = $id;
// редирект с ID на URL
// ------------------------------------------------------------------------------
if (App::isInt($slug)) {
$blog = $this->publicationRepository->findOneBy(['id' => $slug]);
if (!$blog) {
throw new NotFoundHttpException('Not found.');
}
$url = UrlHelper::genUrlBlogSingle($blog);
if (!$url) {
throw new NotFoundHttpException('Not found.');
}
return new RedirectResponse($url, 301);
}
// ------------------------------------------------------------------------------
$oBlogData = new BlogShowData($slug, $preview, $locale);
// если блог не найден, сначала, то проверяем редиректы
if (!$oBlogData->getData()) {
if ($newSlug = $oBlogData->findNewSlug()) {
return new RedirectResponse($oBlogData->getUrl($newSlug), 301);
}
throw new NotFoundHttpException('Not found.');
}
if ($oBlogData->getSlug() !== $slug) {
// если смена локали, то проверяем на предмет блогов доставки, что бы редиректы корректно выставить
if (in_array($oBlogData->getId(), ['2239','2232'])) {
// https://te2.remote.team/discus/7D0B4465-82E4-820E-BFF0-F8A245ED8996
if (App::getCurCountry() === 'ru') {
$newSlug = $this->publicationRepository->getKey(2239, $locale);
} else {
$newSlug = $this->publicationRepository->getKey(2232, $locale);
}
$newUrl = $this->generateUrl('app_publication_single', ['id' => $newSlug]);
} else {
$newUrl = $oBlogData->getUrl();
}
return new RedirectResponse($newUrl, 301);
}
if (!$oBlogData->isShowSite()) {
// разрешаем смотреть только админам
if (!App::isRole('ROLE_ADMIN')) {
throw new NotFoundHttpException('Page not found.');
}
}
// редиректим на новый блог экспресс образцов
if (!$oBlogData->isExhibition() and $oBlogData->getId() == 2214) {
if ($newUrl = $this->publicationRepository->getUrlBlogExpressSamples(true)) {
return new RedirectResponse($newUrl, 302);
} else {
throw new NotFoundHttpException('Page not found.');
}
}
// Обновление статистики просмотров
$oBlogData->updView();
$oTrans = App::getTranslator();
$settingsCount = [
0 => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%', '%count%' => 0], null),
1 => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%', '%count%' => 1], null),
2 => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%', '%count%' => 2], null),
3 => $oTrans->trans('catalog.settings.count_result', ['%cnt%' => '%cnt%', '%count%' => 3], null),
];
$data = $oBlogData->getData();
if (isset($data['body'])) {
if (!isset($blog) || !$blog) {
/** @var Publication $blog */
$blog = $this->publicationRepository->find($oBlogData->getId());
if (!$blog) {
throw new InternalServerErrorException("Не нашли в базе блог по id {$oBlogData->getId()}");
}
}
$this->calendarService->insertHolidays($oBlogData, $blog);
}
/** @var SocialStatRepository $socialStatRepo */
$socialStatRepo = App::getRepository('WebBundle:SocialStat');
$social = $socialStatRepo->getStatLoginToken($locale);
$oBlogData->setBody(LocaleHelper::fixLink($oBlogData->getBody()));
return $this->render('@Web/Publication/show.html.twig', [
'blog' => $oBlogData,
'settingsCount' => $settingsCount,
'social' => $social,
]);
}
/**
* Добавление лайка к пибликации.
*
* @param $id
*
* @return Response
*
* @throws NonUniqueResultException
* @throws Exception
*/
public function likeAction($id)
{
/** @var Publication $publication */
$publication = App::getRepository('WebBundle:Publication')->findOneBy(['id' => $id]);
$token = UserHelper::getInstance()->getToken();
/** @var PublicationLikeRepository $repoPublicationLike */
$repoPublicationLike = App::getRepository('WebBundle:PublicationLike');
$publicationLike = $repoPublicationLike->getPublicationLike($token, $id);
if (!$publicationLike) {
/** @var PublicationLike $publicationLike */
$publicationLike = new PublicationLike();
$publicationLike->setToken($token);
$publicationLike->setPublication($publication);
$em = $this->getDoctrine()->getManager();
$em->persist($publicationLike);
$em->flush();
return new JsonResponse(['status' => 1, 'count' => ($publication->getLikes()->count()), 'token' => $token]);
} else {
$publication->getLikes()->removeElement($publicationLike);
$em = $this->getDoctrine()->getManager();
$em->remove($publicationLike);
$em->persist($publication);
$em->flush();
return new JsonResponse(['status' => 0, 'count' => ($publication->getLikes()->count()), 'token' => $token]);
}
}
/**
* Для слайдера.
*
* @param int $page
* @param int $limit
* @param string $innerBlock
*
* @return Response
*/
public function pageAction($page = 1, $limit = 8, $innerBlock = '')
{
$blogs = $this->publicationService
->page((int) $page, (int) $limit, App::getCurLocale(), $innerBlock);
return $this->render('@Web/Publication/page.html.twig', ['blogs' => $blogs]);
}
}