<?php
namespace App\Controller;
use App\Entity\Category;
use App\Form\Type\ProductSearchFiltersType;
use App\Helper\VeltisControllerTrait;
use App\Repository\ArticleRepository;
use App\Repository\AvailabilityRepository;
use App\Repository\BannerRepository;
use App\Repository\CategoryRepository;
use App\Repository\FurnitureTypeRepository;
use App\Repository\NewsRepository;
use App\Repository\ProductParameterRepository;
use App\Repository\ProductRepository;
use App\Repository\ProductViewRepository;
use App\Repository\WorkingHoursRepository;
use App\Services\CompareManager;
use App\Services\PasswordProtectedService;
use App\Services\SearchManager;
use Doctrine\Common\Collections\ArrayCollection;
use Knp\Component\Pager\PaginatorInterface;
use Liip\ImagineBundle\Service\FilterService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
class CategoryController extends AbstractController
{
use VeltisControllerTrait;
/**
* @Route("/{slug}/{id}/c/{av24h}", name="category", defaults={"av24h": null})
*/
public function indexAction(Request $request, CategoryRepository $categoryRepository, ProductRepository $productRepository, PaginatorInterface $paginator, FurnitureTypeRepository $furnitureTypeRepository, SessionInterface $session, ProductViewRepository $productViewRepository, CompareManager $compareManager, PasswordProtectedService $passwordProtectedService)
{
if ($passwordProtectedService->isPasswordProtected()) {
return $this->redirectToRoute('password_protected');
}
$categories = $categoryRepository->getMainCategories($request->getLocale(), [Category::TYPE_24h, Category::TYPE_SZOK_CENOWY])->getQuery()->getResult();
$furnitureTypes = $furnitureTypeRepository->getForCategory($request->getLocale())->getQuery()->getResult();
$categoryQuery = $categoryRepository->getCategories($request->getLocale(), [$request->attributes->get('id')])->getQuery()->getResult();
if (isset($categoryQuery[0]) and count($categoryQuery) == 1) {
/** @var $category Category */
$category = $categoryQuery[0];
} else {
throw new NotFoundHttpException();
}
if ($request->attributes->get('slug') !== $category->translate($request->getLocale())->getSlug()) {
return $this->redirect($this->generateUrl('category', ['id'=>$category->getId(), 'slug'=>$category->translate($request->getLocale())->getSlug()]), 301);
}
if ($category->getDeletedBy()) {
throw new NotFoundHttpException();
}
foreach ($category->getLangParams() as $langParam) {
if ($langParam->getLanguage()->getLocale() == $request->getLocale()) {
if ($langParam->getVisible() == false && $category->getId() != Category::TYPE_SZOK_CENOWY && $category->getId() != Category::TYPE_NEW_PRODUCTS && $category->getId() != Category::TYPE_BESTSELLERS && $category->getId() != Category::TYPE_24h && $category->getId() != 272) {
throw new NotFoundHttpException();
}
}
}
$gclid = '';
if ($request->query->get('gclid')) {
$gclid = '&gclid='.$request->query->get('gclid');
}
// search engine
if ($request->attributes->get('id') == 1 and $request->query->get('search_text')) {
return new RedirectResponse($this->generateUrl('search').'?query='.$request->query->get('search_text').$gclid);
}
$form = $this->createForm(
ProductSearchFiltersType::class
);
$form->handleRequest($request);
$searchData = [];
if ($form->isSubmitted()) {
$searchData = $form->getData();
}
$searchData['locale'] = $request->getLocale();
if ($request->attributes->get(('av24h'))) {
if ($request->attributes->get('av24h') != '24h') {
throw new NotFoundHttpException();
}
$arr = new ArrayCollection();
$arr->add($this->em()->getRepository('App:Availability')->find(1));
$arr->add($this->em()->getRepository('App:Availability')->find(5));
$arr->add($this->em()->getRepository('App:Availability')->find(15));
$searchData['availability'] = $arr;
}
if ($category->getId() == Category::TYPE_SZOK_CENOWY) {
$products = $productRepository->getForPromotions($category, $searchData)->getQuery();
} elseif ($category->getId() == Category::TYPE_NEW_PRODUCTS) {
$products = $productRepository->getForNewProducts($category, $searchData)->getQuery();
} elseif ($category->getId() == Category::TYPE_BESTSELLERS) {
$products = $productRepository->getForBestsellersProduct($category, $searchData)->getQuery();
} else {
$products = $productRepository->getForCategory($category, $searchData)->getQuery();
}
$lastViewed = $productViewRepository->getLastViewed($session->getId(), $request->getLocale())->getQuery()->getResult();
$pagination = $paginator->paginate($products, $request->query->getInt('page', 1), $session->get('productsPerPage',30), ['wrap-queries'=>true]);
return $this->render('frontend/category/category.html.twig', [
'categories' => $categories,
'furnitureTypes' =>$furnitureTypes,
'lastViewed' => $lastViewed,
'language' => $this->resolveLanguage($request->getLocale()),
'locale' => $request->getLocale(),
'products' => $pagination,
'compareIds' => $compareManager->getIdsCompareProducts(),
'searchData' => $searchData,
'form' => $form->createView(),
'category' => $category,
'productsPerPage' => $session->get('productsPerPage',30),
]);
}
/**
* @Route("/search/query", name="search")
*/
public function searchAction(Request $request, CategoryRepository $categoryRepository, ProductRepository $productRepository, PaginatorInterface $paginator, FurnitureTypeRepository $furnitureTypeRepository, SessionInterface $session, ProductViewRepository $productViewRepository, CompareManager $compareManager, SearchManager $searchManager)
{
$categories = $categoryRepository->getMainCategories($request->getLocale(), [Category::TYPE_24h, Category::TYPE_SZOK_CENOWY])->getQuery()->getResult();
$furnitureTypes = $furnitureTypeRepository->getForCategory($request->getLocale())->getQuery()->getResult();
$form = $this->createForm(
ProductSearchFiltersType::class
);
$form->handleRequest($request);
$searchData = [];
$searchData['query'] = '';
if ($form->isSubmitted()) {
$searchData = $form->getData();
}
$searchData['locale'] = $request->getLocale();
if ($request->query->get('query')) {
$searchData['query'] = trim($request->query->get('query'));
}
if (!isset($searchData['query']) and !$request->query->has('productProducer')) {
//return new RedirectResponse($this->generateUrl('homepage'));
}
//handle phrase query counter
if ($request->query->getInt('page', 1) == 1 or !$request->query->has('page')) {
$searchManager->countSearch(strtolower($searchData['query']), $this->resolveLanguage($request->getLocale()));
}
//handle replace query for different query based on settings in marketing section
$searchData['query'] = $searchManager->format(strtolower($searchData['query']), $this->resolveLanguage($request->getLocale()));
if ($searchData['query'] instanceof RedirectResponse) {
return $searchData['query'];
}
//logo click
if ($request->query->get('productProducer')) {
$searchData['productProducer'] = (int)$request->query->get('productProducer');
}
$products = $productRepository->searchStore($searchData);
$pagination = $paginator->paginate($products, $request->query->getInt('page', 1)/*page number*/, $session->get('productsPerPage',30), ['wrap-queries'=>true]);
$ids = [];
$prods = [];
foreach ($pagination as $product) {
$ex = explode(" ", $searchData['query']);
foreach ($ex as $e) {
$lowerName = strtolower($product[0]->getName());
$lowerQuery = strtolower($e);
$exName = explode(" ", $lowerName);
foreach ($exName as $exPartName) {
if ($exPartName === $lowerQuery and !in_array($product[0]->getId(), $ids)) {
$prods[] = $product;
$ids[] = $product[0]->getId();
}
}
}
}
foreach ($pagination as $product) {
if (!in_array($product[0]->getId(), $ids)) {
$prods[] = $product;
$ids[] = $product[0]->getId();
}
}
return $this->render('frontend/category/search.html.twig', [
'categories' => $categories,
'furnitureTypes' =>$furnitureTypes,
'language' => $this->resolveLanguage($request->getLocale()),
'products' => $pagination,
'prodsMod' => $prods,
'productsPerPage' => $session->get('productsPerPage',30),
'compareIds' => $compareManager->getIdsCompareProducts(),
'searchData' => $searchData,
'form' => $form->createView(),
]);
}
/**
* @Route("/s/search/1/c", name="search_old_site_redirect")
*/
public function searchRedirectOldSiteAction(Request $request)
{
if ($request->query->get('search_text')) {
$gclid = '';
if ($request->query->get('gclid')) {
$gclid = '&gclid='.$request->query->get('gclid');
}
return new RedirectResponse($this->generateUrl('search').'?query='.$request->query->get('search_text').$gclid, 301);
}
if ($request->query->get('category_id')) {
$category = $this->em()->getRepository('App:Category')->find($request->query->get('category_id'));
if ($category) {
return new RedirectResponse(
$this->generateUrl('category', ['id' => $category->getId(), 'slug' => $category->getSlug()]), 301
);
}
}
return new RedirectResponse($this->generateUrl('homepage'));
}
/**
* @Route("/change-products-per-page", name="change_products_per_page")
*/
public function changeProductsPerPageAction(Request $request, SessionInterface $session)
{
if ($request->request->get('productsPerPage') and is_numeric($request->request->get('productsPerPage'))) {
$session->set('productsPerPage', (int)$request->request->get('productsPerPage'));
}
return new JsonResponse([]);
}
/**
* @Route("/search/auto-complete/query", name="search_autocomplete")
*/
public function searchAutoCompleteAction(Request $request, \Symfony\Component\Asset\Packages $assetsManager, FilterService $filterService, CategoryRepository $categoryRepository, ProductRepository $productRepository, PaginatorInterface $paginator, FurnitureTypeRepository $furnitureTypeRepository, RouterInterface $router, ProductViewRepository $productViewRepository, CompareManager $compareManager, SearchManager $searchManager)
{
$query = $request->query->get('query');
$searchData = [];
$searchData['query'] = $query;
$searchData['locale'] = $request->getLocale();
//handle replace query for different query based on settings in marketing section
$searchData['query'] = $searchManager->format(strtolower($searchData['query']), $this->resolveLanguage($request->getLocale()));
if ($searchData['query'] instanceof RedirectResponse) {
return $searchData['query'];
}
$products = $productRepository->searchStore($searchData);
$pagination = $paginator->paginate($products, $request->query->getInt('page', 1)/*page number*/, 30, ['wrap-queries'=>true]);
$json = [];
foreach ($pagination as $product) {
/**
* array:9 [▼
0 => Product {#33587 ▶}
"isNew" => false
"mainPhoto" => "krzeslo-tulipan-529.jpeg"
"isBestseller" => null
"vatId" => 1
"currencySign" => "zł"
"currencyId" => 1
"priceDescription" => "100 - 113"
"priceCrossed" => null
]
*/
$path = $assetsManager->getUrl('/images/product/'.$product['mainPhoto']);
if (file_exists(getcwd()."/images/product/".$product['mainPhoto'])) {
$resourcePath = $filterService->getUrlOfFilteredImage($path, 'smallProdImageQuality');
} else {
$resourcePath = false;
}
if ($request->getLocale() == 'ro') {
$product['priceDescription'] = str_replace(".", ",", $product['priceDescription']);
}
if ($resourcePath) {
$url = $router->generate('product', ['slug'=>$product[0]->getSlug(), 'id'=>$product[0]->getId()]);
$json[] = ['url'=>$url, 'imageUrl'=>$resourcePath, 'price'=>$product['priceDescription'].' '.$product['currencySign'], 'value'=>$product[0]->getName(), 'data'=>$product[0]->getId()];
}
}
return new JsonResponse(['suggestions'=>$json]);
}
}