<?php
namespace WebBundle\Controller;
use Exception;
use FlexApp\Constant\TimeConstant;
use FlexApp\Helper\SecuriHelper;
use Memcache;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use WebBundle\Constant\CookieKeysConstant;
use WebBundle\Entity\Article;
use WebBundle\Entity\Collection;
use WebBundle\Helper\App;
use WebBundle\Helper\ArticleSettingsHelper;
use WebBundle\Helper\CookieHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Helper\UserHelper;
use WebBundle\Repository\CollectionAlsoViewedRepository;
use WebBundle\Repository\CollectionRepository;
use WebBundle\Repository\FilterRepository;
use WebBundle\Repository\IdeaRepository;
use WebBundle\Service\CollectionService;
/**
* Class CollectionController
* @package WebBundle\Controller
*/
class CollectionController extends ExtendedController
{
/** @required */
public CollectionService $collectionService;
private CollectionRepository $collectionRepository;
private FilterRepository $filterRepository;
private IdeaRepository $ideaRepository;
private CollectionAlsoViewedRepository $collectionAlsoViewedRepository;
public function __construct(
CollectionRepository $collectionRepository,
FilterRepository $filterRepository,
CollectionAlsoViewedRepository $collectionAlsoViewedRepository,
IdeaRepository $ideaRepository
) {
parent::__construct();
$this->collectionRepository = $collectionRepository;
$this->filterRepository = $filterRepository;
$this->collectionAlsoViewedRepository = $collectionAlsoViewedRepository;
$this->ideaRepository = $ideaRepository;
}
/**
* Для редиректа с неполной ссылки на коллекцию
* @param string $factoryUrl
* @return Response
*/
public function factoryRedirectAction(string $factoryUrl): Response
{
return $this->redirect($this->generateUrl('app_catalog', [
'key' => StrHelper::toLower($factoryUrl),
'_locale' => App::getCurLocale(true),
]), 301);
}
/**
* Для редиректа кривых ссылок пинтереса
* @param string $fUrl
* @param string $cUrl
* @param string|null $type
* @param string|null $elId
* @return RedirectResponse
* @throws Exception
*/
public function noTileLinkAction(string $fUrl, string $cUrl, string $type = null, string $elId = null): RedirectResponse
{
$oServiceColl = App::getContainer()->get('app.service.collection');
$collection = $oServiceColl->findCollectionInDb($fUrl, $cUrl);
if ($collection) {
return $this->redirect($this->generateUrl('app_collection', [
'_locale' => App::getCurLocale(true),
'factoryUrl' => $fUrl,
'collectionUrl' => $cUrl,
'type' => $type,
'elementId' => $elId,
]), 301);
} else {
throw $this->createNotFoundException('Not found');
}
}
/**
* Генерирует список присвоенных коллекции свойств
* @param $coll
* @return Response
* @throws Exception
*/
public function settingsListAction($coll): Response
{
$collection = $this->collectionRepository->getCollectionForInformer((int) $coll);
$settings = $this->collectionService->getSettings($collection);
return new Response($settings);
}
/**
* @param string $key
* @param array $param
* @return mixed
* @throws Exception
*/
public function transS(string $key, array $param = [])
{
return str_replace(
['(', ')', '\'', '"', '`', ',', '?', '!', ';', ':', '\\', '/'],
'',
App::getTranslator()->trans($key, $param, 'messages', 'en')
);
}
/**
* @param int $collectionId
* @return Response
* @throws Exception
*/
function getInformerAction(int $collectionId): Response
{
$typeDO = true;
$minPrice = 0;
$collection = $this->collectionRepository->getCollectionForInformer($collectionId);
$settings = $this->collectionService->getSettings($collection);
/** @var Article $article */
foreach ($collection['articles'] ?? [] as $article) {
if (!empty($article['measure']) && $article['measure']['id'] == 1) {
$typeDO = false;
break;
} else {
$newMinPrice = LocaleHelper::getPrice($article);
if ($minPrice > $newMinPrice && $newMinPrice != 0 || $minPrice == 0) {
$minPrice = $newMinPrice;
}
}
}
$prMin = LocaleHelper::getPrMin($collection);
if ($typeDO) {
$price = LocaleHelper::floatSign($minPrice) . ' ' . LocaleHelper::getCurrency() .
'/' . $this->get('translator')->trans('measure_unit');
} else {
$measure = LocaleHelper::measureGb() ? 'measure_ft' : 'measure_mq';
$price = LocaleHelper::floatSign($prMin) . ' ' . LocaleHelper::getCurrency() .
'/' . $this->get('translator')->trans($measure);
}
$reviews = $this->get('app.service.reviews')->getReviewByCollection($collection['code']);
// проверяем наличие выставок и получаем по ним данные, если есть
$exhibitions = [];
if (!empty($collection['exhibition'])) {
$exhibitions = $this->filterRepository->getExhibitions($collection['exhibition']);
}
$collection['exhibition'] = $exhibitions;
return $this->render(
'@Web/Collection/collection_info.html.twig',
[
'price' => $price,
'collection' => $collection,
'setting' => $settings,
'reviews' => $reviews,
]
);
}
/**
* @param Request $request
* @return JsonResponse
* /json/collection/get?unid=BC51EE40C7F24DEFC3257800001E341D&hash=11246411fec5b14b69f109ad2a4b4dff (хеш на дату 12/07/2016)
* @throws Exception
*/
public function getAction(Request $request): JsonResponse
{
$factoryUnid = $request->get('unid');
if (!SecuriHelper::checkHashPortal($request->get('hash'))) {
return new JsonResponse(['success' => false]);
}
$collections = $this->collectionRepository->getCollectionsByFactoryUnid($factoryUnid);
$res = [];
/** @var Collection $collection */
foreach ($collections as $collection) {
$col = [
'id' => $collection->getId(),
'name' => $collection->getName(),
'unid' => $collection->getUnid(),
'code' => $collection->getCode(),
'articles' => [],
];
/** @var Article $article */
foreach ($collection->getArticles() as $article) {
$col['articles'][] = [
'id' => $article->getId(),
'name' => $article->getName(),
'code' => $article->getCode(),
'size' => $article->getSizeX() . '*' . $article->getSizeY(),
];
}
$res[] = $col;
}
return new JsonResponse(['unid' => $factoryUnid, 'collections' => $res]);
}
/**
* @param $collectionId
* @return Response
* @throws Exception
*/
public function alsoViewedAction($collectionId): Response
{
$session = App::getRequest()->getSession();
if ($session->get('cid') && $session->get('cid') != $collectionId) {
$this->collectionAlsoViewedRepository->setCollectionAlsoViewed($collectionId, $session->get('cid'));
}
$session->set('cid', $collectionId);
$minElem = 5;
$maxElem = 16;
#todo при переходе на sf4 проанализировать и переделать скорее всего с ссылками на коллекции через join
$ides = $this->collectionAlsoViewedRepository->getCollectionAlsoViewed($collectionId);
$idesCount = count($ides);
if ($idesCount > 0) {
$viewedAlias = $this->collectionRepository->getCollectionAlsoViewedNative($ides, $maxElem);
} else {
$viewedAlias = [];
}
if ($idesCount < $minElem) {
$collections = $this->collectionRepository->getCollectionAlsoViewedNative(array_merge([$collectionId], $ides), ($minElem - count($ides)), 'NOT IN');
foreach ($collections as $elem) {
$ides[] = $elem['id'];
}
} else {
$collections = [];
}
$dependentCollections = array_merge($viewedAlias, $collections);
// получаем данные по наградам
foreach ($dependentCollections as $i => $dc) {
if (!empty($dc['awards'])) {
$aAwards = $this->filterRepository->getAwards($dc['awards']);
if ($aAwards) {
$dependentCollections[$i]['awards'] = $aAwards;
}
}
}
$favorites = $this->ideaRepository->getInteriorsIdeasByToken(UserHelper::getInstance()->getToken());
return $this->render(
'@Web/Collection/most_viewed.html.twig',
[
'linkAlsoColl' => str_replace('%26', '&', $this->generateUrl(
'app_catalog',
[
'_locale' => App::getCurLocale(true),
'key' => 'coll',
'subkey' => $collectionId,
]
)),
'fav' => $favorites,
'mostWatchedCollections' => $dependentCollections,
]
);
}
/**
* @param int $id
* @param int|null $filter
* @return array|false|string|JsonResponse|Response
* @throws Exception
*/
public function articleSettingsListAction(int $id, ?int $filter = 0)
{
$memKey = md5($id . $filter . '3' . App::getCurLocale('true') . CookieHelper::get(CookieKeysConstant::CURRENCY) .
CookieHelper::get(CookieKeysConstant::MEASURE) . CookieHelper::get(CookieKeysConstant::MEASURE_FT));
$memcache = new Memcache;
$memcache->connect(App::getParameter('memcache_host'), App::getParameter('memcache_port'));
$response = $memcache->get($memKey);
if ($response !== false) {
return $response;
}
$settings = ArticleSettingsHelper::getArticleSettings($id, null, null, null, !empty($filter));
$desc = $settings['description'];
unset($settings['description']);
if ($filter == 1) {
$response = new JsonResponse($settings);
} else {
unset($settings['filters']);
$response = $this->render(
'@Web/Collection/article-setting.html.twig',
['desc' => str_replace('¶', ' ', $desc), 'settings' => $settings]
);
}
$response->setCache(['no_cache' => true]);
$memcache->add($memKey, $response, false, TimeConstant::WEEK);
return $response;
}
}