<?php
// src/Controller/DefaultController.php
namespace App\Controller;
use App\Entity\Comment;
use App\Entity\Product;
use App\Entity\ProductCategory;
use App\Entity\ProductGroup;
use App\Entity\ProductHasProductSpecificationValue;
use App\Entity\ProductSpecification;
use App\Entity\ProductSpecificationValue;
use App\Entity\SeoFormula;
use App\Repository\ProductCategoryRepository;
use App\Repository\ProductHasProductSpecificationValueRepository;
use App\Repository\ProductRepository;
use App\Repository\ProductSpecificationValueRepository;
use App\Services\CartManager;
use App\Services\LikesService;
use App\Services\MenuService;
use App\Services\SearchService;
use App\Services\SeoFormulaService;
use App\ZorrovAdmin\ApiBundle\Controller\ApiController;
use App\ZorrovAdmin\DashboardBundle\Services\DropshipperBalanceService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProductController extends ApiController
{
/**
* @Route("/category-filters-apply/{slug}/{sort}", name="app_category_filters_apply")
*/
public function categoryFiltersApplyAction($slug, $sort, Request $request)
{
$filterStr = $this->filtersApply($request, $sort);
return $this->redirectToRoute('app_category_show', ['slug' => $slug, 'filters' => $filterStr]);
}
/**
* @Route("/category/{slug}/{filters}", name="app_category_show")
*/
public function categoryShowAction($slug,
CartManager $cartManager,
MenuService $menuService,
ProductSpecificationValueRepository $productSpecificationValueRepository,
ProductCategoryRepository $categoryRep,
ProductHasProductSpecificationValueRepository $productHasSpecificationValueRepository,
LikesService $likesService,
SeoFormulaService $seoFormulaService,
DropshipperBalanceService $dropshipperBalanceService,
$filters = '')
{
if(preg_match('/[A-Z]/', $slug)){
$url = $this->generateUrl('app_category_show',array('slug'=>strtolower($slug),'filters'=>$filters));
return $this->redirect($url, 301);
}
$category = $categoryRep->findOneBySlug($slug);
if($category->hasShownGrandChildren()
or ($category->getParent() and $category->hasChildren() and $category->getShowChildrenOnWebsite())){
// $categories = $categoryRep->findThreeLevelWithSeries($category);
// $preparedCategories = $menuService->generateChildren($categories, [],'app_category_show');
return $this->render('frontend/product/category_list.html.twig', [
'slug'=>$slug,
// 'categories'=>$preparedCategories,
// 'categoryId' => $category->getId(),
'mainCategory'=>$category,
]);
}
// else{
// $categories = $categoryRep->findTwoLevelWithSeries($category);
// $preparedCategories = $menuService->generateOneLevelChildren($categories, [],'app_category_show');
// return $this->render('frontend/product/category_small_list.html.twig', [
// 'categories'=>$preparedCategories,
// 'categoryId' => $category->getId(),
// 'category'=>$category,
// ]);
// }
if(!$category){
throw $this->createNotFoundException('Category does not exist');
}
$constructor = $category->getCategoryUsedForGeneration();
$cart = $cartManager->getCurrentCart($this->getUser());
$cartProducts = $this->getDoctrine()->getRepository(Product::class)
->getAllCartProductsIndexById($cart->getId());
$seo = $this->seoCategoryData($category,$seoFormulaService);
$filterStr = $filters;
$filters = $this->prepareFilters($filters);
if(!$filters)
throw $this->createNotFoundException('Filters does not exist');
$specifications = $this->getDoctrine()->getRepository(ProductSpecification::class)
->findByValuesIds($filters['filters']);
$filterTexts = $this->prepareFilterTexts($specifications);
$seoTitle = $this->prepareSeoTitle($filterTexts,$filters['page']);
$count = (int)$this->getParameter('product_on_page');
$products = $this->getProducts($category, $filters, $specifications, $count);
$last = (int)ceil($products['allProductsCount']['1']/$count);
if($category->checkIfGroupsIn()){
$productsSpecValues = $productSpecificationValueRepository->findAllByGroups($products['productIdsUnLimited']);
$productsSpecValuesCount = $productHasSpecificationValueRepository->countAllGroupsBySpecificationValues($products['productIdsUnLimited']);
}
else{
$productsSpecValues = $productSpecificationValueRepository->findAllByProducts($products['productIdsUnLimited']);
$productsSpecValuesCount = $productHasSpecificationValueRepository->countAllProductsBySpecificationValues($products['productIdsUnLimited']);
}
// dump($products['productIdsUnLimited']);
// dump($productsSpecValues);
// dump($filters);
// dump($productsSpecValuesCount);
// die();
$specifications = $this->prepareSpecificationArray($productsSpecValues, $filters['filters'], $productsSpecValuesCount);
$wishlist = $likesService->getStorageIds();
$filterStr = $this->prepareFilterStr($filterStr);
$filterFilterNextPageStr = $this->prepareFilterNextPageText($filterStr, $filters, $last);
$productsCount = $this->productsCountInit($filters, $count, $products['allProductsCount'], $last);
// dump($productsCount); die();
$productsLimited = $dropshipperBalanceService->checkPrices($products['productsLimited'], $this->getUser());
dump($filters);
dump($filterStr);
die();
return $this->render('frontend/product/category.html.twig', [
'category' => $category,
'categoryId' => $category->getId(),
'constructor' => $constructor,
'products' => $productsLimited,
'productsIdsUnLimitedStr' => implode(',',$products['productIdsUnLimited']),
'productsIdsUnLimited' => $products['productIdsUnLimited'],
'filters' => $filters,
'filterStr' => $filterStr,
'filterFilterNextPageStr' => $filterFilterNextPageStr,
'filterTexts' => $filterTexts,
'seoTitle' => $seoTitle,
'cart' => $cart,
'count' => $count,
'productsCount' => $productsCount,
'last' => $last,
'seo' => $seo,
'wishlist' => $wishlist,
'orderProducts' => array_keys($cartProducts),
'specifications' => $specifications,
// 'pagesInRange' => $pagesInRange
]);
}
/**
* @Route("/category-step/{slug}/{filters}", name="app_category_steps")
*/
public function categoryStepAction($slug,
Request $request,
CartManager $cartManager,
LikesService $likesService,
DropshipperBalanceService $dropshipperBalanceService,
$filters = '')
{
$filterStr = $filters;
if(preg_match('/[A-Z]/', $slug)){
$url = $this->generateUrl('app_category_show',array('slug'=>strtolower($slug)));
return $this->redirect($url, 301);
}
$filters = $this->prepareFilters($filters);
$activePages = $this->activePagesInit($request, $filters);
$specifications = $this->getDoctrine()->getRepository(ProductSpecification::class)
->findByValuesIds($filters['filters']);
$cart = $cartManager->getCurrentCart($this->getUser());
$cartProducts = $this->getDoctrine()->getRepository(Product::class)
->getAllCartProductsIndexById($cart->getId());
$category = $this->getDoctrine()->getRepository(ProductCategory::class)
->findOneBySlug($slug);
$count = (int)$this->getParameter('product_on_page');
$products = $this->getProducts($category, $filters, $specifications, $count);
// $products = $this->getDoctrine()->getRepository(Product::class)
// ->findProductsByCategoryMinimized($category->getId(), $filtersPrepared, $filters['sort'], $filters['page']-1, $count);
// dump($products); die();
$last = (int)ceil($products['allProductsCount']['1']/$count);
$wishlist = $likesService->getStorageIds();
$filterStr = $this->prepareFilterStr($filterStr);
$filterFilterNextPageStr = $this->prepareFilterNextPageText($filterStr, $filters, $last);
$productsCount = $this->productsCountInit($filters, $count, $products['allProductsCount'], $last);
$productsLimited = $dropshipperBalanceService->checkPrices($products['productsLimited'], $this->getUser());
$data = array(
'products' => $this->renderView('frontend/product/category_step.html.twig', [
'category'=>$category,
'products'=>$productsLimited,
'filters'=>$filterFilterNextPageStr,
'current'=>$filters['page'],
'last' => $last,
'orderProducts' => array_keys($cartProducts)
]),
'pagination' => $this->renderView('frontend/parts/pagination.html.twig', [
'slug'=> $slug,
'activePages'=> $activePages,
'filters'=> $filterStr,
'current'=> $filters['page'],
'last' => $last
]),
'buttonCount' => $productsCount
);
return $this->respond($data);
}
/**
* @Route("/product/{slug}", name="app_product_show")
* @Route("/product/custom/{slug}", name="app_product_show_custom")
*/
public function productShowAction($slug,
CartManager $cartManager,
LikesService $likesService,
SeoFormulaService $seoFormulaService,
Request $request)
{
$cart = $cartManager->getCurrentCart($this->getUser());
$product = $this->getDoctrine()->getRepository(Product::class)
->findProductBySlug($slug);
if(!$product){
$products = $this->getDoctrine()->getRepository(Product::class)
->findProductByTranslationSlug($slug);
if($products)
$product = $products[0];
}
if($product->getCustom()){
$product = $cartManager->recalculateCustomProductPrice($product);
}
$productSpecifications = $this->getDoctrine()->getRepository(ProductHasProductSpecificationValue::class)
->findSpecificationsForProductPage($product);
if(!$product){
throw $this->createNotFoundException('The product does not exist');
}
$constructor = $product->getCategory()->getCategoryUsedForGeneration();
$wishlistIds = $likesService->getStorageIds();
$cartProducts = $this->getDoctrine()->getRepository(Product::class)
->getAllCartProductsIndexById($cart->getId());
$seo = $this->seoProductData($product,$seoFormulaService);
$models = $this->getModels($product);
$gallery = $this->getProductGallery($product);
// $suggestions = $this->getDoctrine()->getRepository(Product::class)
// ->getSuggstionsProductsByCategory($cart->getId());
// $number = random_int(0, 100);
// return new Response(
// '<html><body>Lucky number: '.$number.'</body></html>'
// );
// dump($productSpecifications); die();
$info = $this->getInfo($product, $request->getLocale());
return $this->render('frontend/product/product.html.twig', [
'product'=>$product,
'gallery'=>$gallery,
'constructor' => $constructor,
'models' => $models,
'info' => $info,
'categoryId' => $product->getCategory()->getId(),
'productSpecificationValues'=>$productSpecifications,
'seo'=>$seo,
'wishlist' => $wishlistIds,
'orderProducts' => array_keys($cartProducts),
]);
}
/**
* @Route("/you-may-like-it/{id}", name="app_you_may_like_it")
*/
public function youMayLikeItAction($id, CartManager $cartManager, TranslatorInterface $translator,
DropshipperBalanceService $dropshipperBalanceService)
{
$cart = $cartManager->getCurrentCart($this->getUser());
// $product = $this->getDoctrine()->getRepository(Product::class)
// ->find($id);
$cartProducts = $this->getDoctrine()->getRepository(Product::class)
->getAllCartProductsIndexById($cart->getId());
$ids = ($cartProducts) ? array_keys($cartProducts) : array();
$ids[] = $id;
$suggestions = $this->getDoctrine()->getRepository(Product::class)
->getRandomSuggestionsProductsNotInCart($ids);
// $number = random_int(0, 100);
// return new Response(
// '<html><body>Lucky number: '.$number.'</body></html>'
// );
$suggestions = $dropshipperBalanceService->checkPrices($suggestions, $this->getUser());
return $this->render('frontend/parts/you_may_like_it.html.twig', [
'products'=>$suggestions,
'blockTitle'=>$translator->trans('product.you_will_like_it',[],'translation')
// 'orderProducts' => array_keys($cartProducts)
]);
}
/**
* @Route("/pattern-on-other-products/{id}", name="app_pattern_on_other_products")
*/
public function patternOnOtherProductsAction($id, TranslatorInterface $translator,
ProductRepository $productRepository,
DropshipperBalanceService $dropshipperBalanceService)
{
$product = $productRepository->find($id);
if(!$product){
throw $this->createNotFoundException('The product does not exist');
}
$patternCategoryConstructor = $product->getPatternCategoryConstructor();
if(!$patternCategoryConstructor){
return new Response();
}
$category = $patternCategoryConstructor->getCategory();
$pattern = $patternCategoryConstructor->getPattern();
$products = $productRepository->getPatternOnOtherProducts($category, $pattern, 20);
$products = $dropshipperBalanceService->checkPrices($products, $this->getUser());
return $this->render('frontend/parts/you_may_like_it.html.twig', [
'patternProducts'=>true,
'products'=>$products,
'blockTitle'=>$translator->trans('product.other_products_with_print',[],'translation')
// 'orderProducts' => array_keys($cartProducts)
]);
}
/**
* @Route("/wishlist-page/", name="app_wishlist_page")
*/
public function wishlistPageAction(LikesService $likesService)
{
$wishlistIds = $likesService->getStorageIds();
// dump($wishlistIds); die();
$wishlistProducts = $this->getDoctrine()->getRepository(Product::class)
->findByIds($wishlistIds);
return $this->render('frontend/product/wishlist-page.html.twig', [
'products' => $wishlistProducts,
'wishlist' => $wishlistIds,
// 'orderProducts' => array_keys($cartProducts)
]);
}
public function wishlistCount(LikesService $likesService)
{
$wishlistCount = $likesService->getWishlistCount();
return new Response($wishlistCount);
}
private function prepareSpecificationArray($values, $filters, $productsSpecValuesCount)
{
$specifications = array();
$productsSpecValuesCountArr = $this->prepareValuesProductCountArray($productsSpecValuesCount);
foreach ($values as $value){
$specification = $value->getProductSpecification();
if(empty($specifications[$specification->getId()])){
$specifications[$specification->getId()] = array(
'title' => $specification->translate()->getTitle(),
'position' => $specification->getPosition() ? $specification->getPosition() : 0,
'values' => array()
);
}
if(!empty($productsSpecValuesCountArr[$value->getId()])){
$specifications[$specification->getId()]['values'][$value->translate()->getValue()] = array(
'id' => $value->getId(),
'value' => $value->translate()->getValue(),
'count' => $productsSpecValuesCountArr[$value->getId()],
'checked' => in_array($value->getId(), $filters)
);
}
}
$result = $specifications;
foreach ($specifications as $key => $specification){
ksort($specification['values']);
$result[$key]['values'] = $specification['values'];
}
//to sort specifications by position
$price = array_column($result, 'position');
array_multisort($price, SORT_DESC, $result);
return $result;
}
private function prepareValuesProductCountArray($productsSpecValuesCountArr)
{
$values = array();
foreach ($productsSpecValuesCountArr as $productsSpecValuesCount){
$values[$productsSpecValuesCount[0]['productSpecificationValue']['id']] = $productsSpecValuesCount[1];
}
return $values;
}
/**
* @Route("/category-list/{slug}", name="app_productcategory_list")
*/
public function categoryListAction($slug, MenuService $menuService, Request $request)
{
$categoryRep = $this->getDoctrine()->getRepository(ProductCategory::class);
$category = $categoryRep->findOneBySlug($slug);
// $preparedCategories = $this->getDoctrine()->getRepository(ProductCategory::class)
// ->findByParentCategoryWithSeriesPrepared($category);
if($category->hasGrandChildren()){
$categories = $categoryRep->findThreeLevelWithSeries($category);
// if($this->getUser() and $this->getUser()->getUsername()=='admin'){
// dump($categories); die();
// }
// dump($categories); die();
$items = $menuService->generateChildrenForCategoryList($categories, $request->getLocale());
$preparedCategories = array(
'items'=>$items,
'title'=>$category->translate()->getTitle()
);
}
else{
$categories = $categoryRep->findTwoLevelWithSeries($category);
$icon = $category->getPoster() ? json_decode($category->getPoster())->default_file : "";
$preparedCategories = array(
// 'items'=>array(
// 'children'=>$menuService->generateChilden($categories),
// 'icon'=>$icon,
// 'label'=> $category->translate()->getTitle(),
// 'url'=> $this->generateUrl('app_category_show',array('slug'=>$slug))
// ),
'items'=>$menuService->generateChilden($categories, $request->getLocale()),
'title'=>$category->translate()->getTitle()
);
}
// dump($preparedCategories); die();
return $this->respond($preparedCategories);
}
/**
* @Route("/add-to-wishlist/{id}", name="app_add_to_wishlist")
*/
public function likesAction($id, LikesService $likesService)
{
$data = array(
'status' => false,
'message' => ''
);
$product = $this->getDoctrine()->getRepository(Product::class)
->find($id);
if(!$product){
$data['message'] = "product doesn't exist";
}
else{
$result = $likesService->addRemoveLike($product, $this->getUser());
if($result){
$data['status'] = true;
$data['isInWishlist'] = $result['status'];
$data['count'] = $result['count'];
$data['cartProductPrice'] = $product->getPrice();
}
else{
$data['message'] = "something went wrong with like service";
}
}
return $this->respond($data);
}
private function prepareFilters($filters)
{
$notFound = !empty($filters);
$prepared = array(
'page' => 1,
'sort' => $this->getParameter('default_sort'),
'filters' => array(),
);
$filterArr = explode(';', $filters);
// dump($filterArr);
// die();
$filterTexts = array();
foreach ($filterArr as $filterItem){
if(strpos($filterItem,'page') !== false) {
$prepared['page'] = (int)str_replace('page=', '', $filterItem);
$notFound = false;
continue;
}
if(strpos($filterItem,'sort') !== false) {
$prepared['sort'] = str_replace('sort=', '', $filterItem);
$notFound = false;
continue;
}
$filterParts = explode('=', $filterItem);
if(count($filterParts) == 2){
if(empty($filterTexts[$filterParts[0]])){
$filterTexts[$filterParts[0]] = array();
}
$filterTexts[$filterParts[0]] = explode(',', $filterParts[1]);
$notFound = false;
}
}
if($filterTexts){
foreach ($filterTexts as $systemName=>$filter){
$values = $this->getDoctrine()->getRepository(ProductSpecificationValue::class)
->findBySystemNamesAndSpecSystemName($systemName,$filter);
$prepared['filters'] = array_merge($prepared['filters'], array_keys($values));
}
}
if($notFound) return null;
return $prepared;
}
private function prepareFilterValues($specifications)
{
$prepared = array();
foreach ($specifications as $id => $specification){
$prepared[$id] = array();
foreach ($specification['values'] as $value){
$prepared[$id][] = $value['id'];
}
}
return $prepared;
}
private function prepareFilterTexts($specifications, $locale = 'ru')
{
$prepared = array();
foreach ($specifications as $specification){
foreach ($specification['values'] as $value){
$prepared[$value['id']] = array(
'specification' => $specification['translations'][$locale]['title'],
'value' => $value['translations'][$locale]['value']
);
}
}
return $prepared;
}
private function prepareSeoTitle($filterTexts,$page)
{
$seoTitle = ' - ';
if(count($filterTexts)){
$seoTitles = array();
foreach ($filterTexts as $filterText){
if(empty($seoTitles[$filterText['specification']])){
$seoTitles[$filterText['specification']] = array();
}
$seoTitles[$filterText['specification']][] = $filterText['value'];
}
// dump($seoTitles);die();
foreach ($seoTitles as $specification => $seoValues){
$seoTitle .= $specification . ': ' . implode(", ", $seoValues). '; ';
}
}
if($page > 1)
$seoTitle .= 'Страница '.$page;
$seoTitle = ' '. trim($seoTitle,'; ');
return $seoTitle == ' -' ? '' : $seoTitle;
}
private function prepareFilterStr($filterStr)
{
$filterStr = trim(explode('page=',$filterStr)[0],';');
$filterStr = trim(explode('sort=',$filterStr)[0],';');
return $filterStr;
}
private function prepareFilterNextPageText($filterStr, $filters, $last)
{
if ($filters['page'] and $filters['page'] != $last){
$filters['page'] += 1;
if($filterStr)
$filterStr .= ';page='.$filters['page'];
else
$filterStr .= 'page='.$filters['page'];
}
if($filters['sort'] and $filters['sort'] != $this->getParameter('default_sort')){
if($filterStr)
$filterStr .= ';sort='.$filters['sort'];
else
$filterStr .= 'sort='.$filters['sort'];
}
return $filterStr;
}
/**
* @Route("/add-view/{id}", name="app_add_view")
*/
public function viewProductAction($id)
{
$data = array(
'status' => false,
'message' => ''
);
$product = $this->getDoctrine()->getRepository(Product::class)
->find($id);
if(!$product){
$data['message'] = "product doesn't exist";
}
else{
$views = $product->getViews();
$product->setViews($views + 1);
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
$data['status'] = true;
}
return $this->respond($data);
}
/**
* @Route("/search", name="app_product_search", methods={"POST"})
*/
public function productSearchAction(Request $request, SearchService $searchService)
{
$search = $search_str = $searchService->sanitaze($request->request->get('value'));
file_put_contents('search_log.txt', $search."\n", FILE_APPEND);
$categoryResults = $searchService->getCategoryResults($search);
$productResults = $searchService->getProductResults($search);
if(!$productResults) {
$search = explode(' ', $search);
$search = implode('|', $search);
$productResults = $searchService->getProductResults($search);
}
$content = $this->renderView('frontend/search/popup.html.twig', [
'productResults' => $productResults,
'categoryResults' => $categoryResults,
'search_str' => $search_str,
]);
$response = new Response;
$response->setContent($content);
return $response;
}
/**
* @Route("/search-filters-apply/{search}/{sort}", name="app_search_filters_apply")
*/
public function searchFiltersApplyAction($search, $sort, Request $request)
{
$filterStr = $this->filtersApply($request, $sort);
return $this->redirectToRoute('app_product_search_result', ['search' => $search, 'filters' => $filterStr]);
}
/**
* @Route("/search/{search}/{filters}", name="app_product_search_result", defaults={"search": "", "filters": ""})
*/
public function productSearchResultAction(Request $request, SearchService $searchService, CartManager $cartManager, $search = '', $filters = '')
{
$filterStr = $filters;
$filters = $this->prepareFilters($filters);
$count = (int)$this->getParameter('product_on_page');
$specifications = $this->getDoctrine()->getRepository(ProductSpecification::class)
->findByValuesIds($filters['filters']);
$filtersPrepared = $this->prepareFilterValues($specifications);
$search = $searchService->sanitaze($search ? : $request->query->get('query'));
$productIdsUnLimited = $searchService->getProductIds($search);
$productQuery = $searchService->getProductQuery($search, $filtersPrepared);
$products = $productQuery
->addOption('max_matches', SearchService::MAX_MATCHES)
->setFirstResult(($filters['page']-1) * $count)
->setMaxResults($count)
->getResults();
if(!sizeof($products)) {
$productQuery = $searchService->getProductVendorCodeQuery($search);
$products = $productQuery
->setFirstResult(($filters['page']-1) * $count)
->setMaxResults($count)
->getResults();
}
$last = (int)ceil($productQuery->getTotalFound()/$count);
$count = ($last <= $filters['page'] + 1 ) ? $productQuery->getTotalFound() % $count : $count;
$cart = $cartManager->getCurrentCart($this->getUser());
$cartProducts = $this->getDoctrine()->getRepository(Product::class)
->getAllCartProductsIndexById($cart->getId());
$productsSpecValues = $this->getDoctrine()->getRepository(ProductSpecificationValue::class)
->findAllByProducts(array_column($productIdsUnLimited, 'id'));
$productsSpecValuesCount = $this->getDoctrine()->getRepository(ProductHasProductSpecificationValue::class)
->countAllProductsBySpecificationValues(array_keys($productIdsUnLimited));
$specifications = $this->prepareSpecificationArray($productsSpecValues, $filters['filters'],$productsSpecValuesCount);
$specifications = array_filter($specifications, function($el) { return !empty($el['values']); });
$filterStr = $this->prepareFilterStr($filterStr);
$filterFilterNextPageStr = $this->prepareFilterNextPageText($filterStr, $filters, $last);
$params = [
'search' => $search,
'products' => $products,
'filters' => $filters,
'filtersStr' => $filterStr,
'filterFilterNextPageStr' => $filterFilterNextPageStr,
'count' => $count,
'last' => $last,
'current' => $filters['page'],
'orderProducts' => array_keys($cartProducts),
'specifications' => $specifications,
];
if($request->isXmlHttpRequest()) {
$params['filtersStr'] = $filterFilterNextPageStr;
$data = [
'products' => $this->renderView('frontend/search/list_items.html.twig', $params),
'pagination' => $this->renderView('frontend/search/pagination.html.twig', [
'filters'=> $filterStr,
'search' => $search,
'current'=> $filters['page'],
'last' => $last,
]),
'buttonCount' => $filters['page'] != $last ? $count : 0,
];
return $this->respond($data);
}
return $this->render('frontend/search/index.html.twig', $params);
}
/**
* @Route("/cover/{slug}", name="app_old_covers_reidirect")
*/
public function oldCoversRedirectAction($slug)
{
$product = $this->getDoctrine()->getRepository(Product::class)
->findPartialByOldSlug($slug);
$url = ($product) ? $this->generateUrl('app_product_show',array('slug'=>$product->translate()->getSlug()))
: $this->generateUrl('app_homepage');
return $this->redirect($url, 301);
}
/**
* @Route("/phone/{slug}", name="app_old_phones_reidirect")
*/
public function oldPhonesRedirectAction($slug)
{
$category = $this->getDoctrine()->getRepository(ProductCategory::class)
->findPartialByOldSlug($slug);
$url = ($category) ? $this->generateUrl('app_category_show',array('slug'=>$category->getSlug()))
: $this->generateUrl('app_homepage');
return $this->redirect($url, 301);
}
private function filtersApply($request, $sort)
{
$filterIds = $request->request->get('specifications');
// dump($filterIds); die();
// foreach ($filterIds as $filterId){
// if(is_string($filterId)){
// return $this->redirectToRoute('app_category_show', ['slug' => $filterId]);
// }
// }
$filtersMin = $this->getDoctrine()->getRepository(ProductSpecificationValue::class)
->findByIdsMinimized($filterIds);
$filters = array();
foreach ($filtersMin as $filterRow){
if(empty($filters[$filterRow['productSpecification']['systemName']])){
$filters[$filterRow['productSpecification']['systemName']] = array();
}
$filters[$filterRow['productSpecification']['systemName']][] = $filterRow['systemName'];
}
// $filters = array_column($filtersMin, 'systemName');
$filterStr = '';
foreach($filters as $key => $filter){
if($filter)
$filterStr .= $key.'='.implode(",", $filter).';';
}
$filterStr = rtrim($filterStr, ";");
// dump($filtersMin);
// dump($filterStr); die();
// $filterStr = ($filters) ? implode(";", $filters) : '';
if($sort and $sort != $this->getParameter('default_sort')){
if($filterStr)
$filterStr .= ';sort='.$sort;
else
$filterStr = 'sort='.$sort;
}
return $filterStr;
}
private function seoCategoryData($category,$seoFormulaService)
{
$seo = array();
$seoFormula = $category->getTreeSeoFormula();
if(!$seoFormula){
$seoFormula = $this->getDoctrine()->getRepository(SeoFormula::class)
->findMainFormula()[0];
}
$categoryTitleFields = array(
'title' => $category->translate()->getTitle(),
'titleForProductCyrillic' => $category->translate()->getTitleForProductCyrillic(),
);
$seo['title'] = $seoFormulaService->getTitle($seoFormula,$categoryTitleFields);
$categoryDescriptionFields = array(
'title' => $category->translate()->getTitle(),
'h1' => $category->translate()->getH1(),
);
$seo['description'] = $seoFormulaService->getDescription($seoFormula,$categoryDescriptionFields);
return $seo;
}
private function seoProductData($product,$seoFormulaService)
{
$seo = array();
$seoFormula = $this->getDoctrine()->getRepository(SeoFormula::class)
->findMainFormula()[0];
$productTitleFields = array(
'title' => $product->translate()->getTitle(),
);
$seo['title'] = $seoFormulaService->getTitle($seoFormula,$productTitleFields);
$productDescriptionFields = array(
'title' => $product->translate()->getTitle(),
);
$seo['description'] = $seoFormulaService->getDescription($seoFormula,$productDescriptionFields);
return $seo;
}
private function activePagesInit($request, $filters)
{
$activePages = array();
$firstPage = 1;
$referer = $request->server->get('HTTP_REFERER');
if(str_contains($referer, 'page=')){
$str = substr($referer, strrpos($referer,'/') + 1);
$firstPage = $this->prepareFilters($str)['page'];
}
if($firstPage != $filters['page']){
for ($i = $firstPage; $i < (int)$filters['page']; $i++ ){
$activePages[] = $i;
}
}
return $activePages;
}
private function productsCountInit($filters, $count, $allProductsCount, $last)
{
$productsCount = $count;
if($last <= $filters['page'] + 1){
if($last < $filters['page'] + 1)
$productsCount = false;
else
$productsCount = ($allProductsCount['1'] % $count) ? $allProductsCount['1'] % $count : $count;
}
return $productsCount;
}
private function getProducts($category, $filters, $specifications, $count)
{
$products = array();
$filtersPrepared = $this->prepareFilterValues($specifications);
if($category->checkIfGroupsIn()){
$products['productsLimited'] = $this->getDoctrine()->getRepository(Product::class)
->findProductsByCategoryMinimized($category->getId(), $filtersPrepared, $filters['sort'],$filters['page'] - 1, $count, true, $category->getDisablePatternSortInCategoryTree());
$products['allProductsCount'] = $this->getDoctrine()->getRepository(ProductGroup::class)
->countProductsByCategoryFiltered($category->getId(),$filtersPrepared);
$products['productIdsUnLimited'] = $this->getDoctrine()->getRepository(ProductGroup::class)
->findUnlimitedGroupsIds($category->getId());
}
else{
$products['productsLimited'] = $this->getDoctrine()->getRepository(Product::class)
->findProductsByCategoryMinimized($category->getId(), $filtersPrepared, $filters['sort'],$filters['page'] - 1, $count,false, $category->getDisablePatternSortInCategoryTree());
$products['allProductsCount'] = $this->getDoctrine()->getRepository(Product::class)
->countProductsByCategoryFiltered($category->getId(),$filtersPrepared);
$products['productIdsUnLimited'] = $this->getDoctrine()->getRepository(Product::class)
->findUnlimitedProductsIds($category->getId());
}
// dump($products); die();
return $products;
}
private function getModels($product)
{
$models = array();
$group = $product->getGroup();
if ($group){
// foreach ($group->getSpecificationValues() as $specificationValue){
// $value = $specificationValue->getProductSpecificationValue();
// if($value->getShowOnWebsite()){
// $models[$specificationValue->getId()] = array(
// 'label'=> $value->translate()->getValue(),
// 'isInStock'=> false,
// 'link'=> 'javascript:void(0)',
// );
// }
// }
foreach ($group->getProducts() as $groupProduct){
$value = $groupProduct->getCreateModelSpecificationValue();
// if ($this->getUser() and $this->getUser()->getUsername() == 'admin'){
// dump($value);
// }
$index = $value->getProductSpecificationValue()->getPosition() ? $value->getProductSpecificationValue()->getPosition() : $value->getId();
$models[$index] = array(
'label'=> $value->getProductSpecificationValue()->translate()->getValue(),
'isInStock'=> $groupProduct->getInStock(),
'active'=> ($product->getId()==$groupProduct->getId()),
'link'=> $this->generateUrl(
'app_product_show', array('slug'=>$groupProduct->getSlug())
),
);
}
ksort($models);
// if ($this->getUser() and $this->getUser()->getUsername() == 'admin'){
// dump($models); die();
// }
}
return $models;
}
private function getInfo($product, $locale)
{
$info = null;
if($product->getType() and $product->getType()->getInfo()
and $product->getType()->getInfo()->getInfoItems()){
$info = array(
'title'=>$product->getType()->getInfo()->getTitle(),
'items'=>array()
);
foreach ($product->getType()->getInfo()->getInfoItems() as $item){
if($item->translate($locale)->getValue()){
$info = $this->getInfoItem($info, $item, $locale);
}
else{
$info = $this->getInfoItem($info, $item, 'ru');
}
}
}
return $info;
}
private function getInfoItem($info, $item, $locale){
$values = explode('/',$item->translate($locale)->getValue());
if(count($values) == 2 and $item->translate($locale)->getParameter()){
$info['items'][] = array(
'label'=>$item->translate($locale)->getParameter(),
'min'=>$values[0],
'max'=>$values[1],
);
}
return $info;
}
private function getProductGallery($product)
{
$gallery = array();
if($product->hasGalleryImages()){
$gallery = $this->getGalleryItems($product->getGalleryImages());
}
if($product->getPatternCategoryConstructor() and
$product->getPatternCategoryConstructor()->hasGalleryImages()){
$gallery = array_merge($gallery,
$this->getGalleryItems($product->getPatternCategoryConstructor()->getGalleryImages()));
}
if($product->isCase() and
$product->getPatternCategoryConstructor() and
$product->getPatternCategoryConstructor()->getPattern() and
$product->getPatternCategoryConstructor()->getPattern()->hasGalleryImages()){
$gallery = array_merge($gallery,
$this->getGalleryItems($product->getPatternCategoryConstructor()->getPattern()->getGalleryImages()));
}
if($product->getType() and
$product->getType()->hasGalleryImages()){
$gallery = array_merge($gallery,
$this->getGalleryItems($product->getType()->getProductsGalleryImages()));
}
return $gallery;
}
private function getGalleryItems($gallery){
$galleryItems = array();
foreach ($gallery as $galleryImage){
if($galleryImage->getShowOnWebsite())
$galleryItems[] = $galleryImage;
}
return $galleryItems;
}
}