src/Controller/ProductController.php line 49

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Enterprise License (PEL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PEL
  13.  */
  14. namespace App\Controller;
  15. use App\Ecommerce\CartManager\GetCurrentCartAction;
  16. use App\Ecommerce\Favorites\GetFavoriteIdsAction;
  17. use App\Ecommerce\Favorites\GetFavoriteListsAction;
  18. use App\Ecommerce\IndexService\ProductSearchQueryApplier;
  19. use App\Ecommerce\RecentProducts\Action\GetRecentProductsIdsAction;
  20. use App\Model\DataObject\Customer;
  21. use App\Model\Product\AbstractProduct;
  22. use App\Model\Product\Category;
  23. use App\Website\Navigation\BreadcrumbHelperService;
  24. use App\Website\LinkGenerator\ProductLinkGenerator;
  25. use Carbon\Carbon;
  26. use Knp\Component\Pager\PaginatorInterface;
  27. use Pimcore\Config;
  28. use Pimcore\Model\DataObject;
  29. use Pimcore\Model\DataObject\FilterDefinition;
  30. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  31. use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
  32. use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\DefaultMysql;
  33. use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ElasticSearch\AbstractElasticSearch;
  34. use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface;
  35. use Pimcore\Model\DataObject\SearchInput;
  36. use Pimcore\Model\DataObject\Service;
  37. use Pimcore\Twig\Extension\Templating\HeadTitle;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\HttpFoundation\Response;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  42. class ProductController extends BaseController
  43. {
  44.     /**
  45.      * @Route("/product/{productname}~p{product}", name="shop-detail", requirements={"productname"="[\w-]+", "product"="\d+"})
  46.      * @param Request $request
  47.      * @param AbstractObject $object
  48.      * @param UrlSlug $urlSlug
  49.      *
  50.      * @return Response
  51.      */
  52.     public function productDetailAction(
  53.         Request $request,
  54.         HeadTitle $headTitleHelper,
  55.         BreadcrumbHelperService $breadcrumbHelperService,
  56.         Factory $ecommerceFactory,
  57.         //SegmentTrackingHelperService $segmentTrackingHelperService,
  58.         AbstractProduct $product,
  59.         ProductLinkGenerator $productLinkGenerator
  60.     ) {
  61.         if (
  62.             !($product)
  63.         ) {
  64.             throw new NotFoundHttpException('Product not found.');
  65.         }
  66.         // Sort allergens per type
  67.         // Breadcrumbs
  68.         $breadcrumbHelperService->enrichProductDetailPage($product);
  69.         $params = ['product' => $product, 'allergens' => json_decode($product->getAllergens(), true)];
  70.         /*
  71.          * CartItems
  72.          */
  73.         /** @var Customer $customer */
  74.         $customer = $this->getUser();
  75.         $cart = (new GetCurrentCartAction())($customer);
  76.         $cartItems = [];
  77.         foreach ($cart->getItems() as $cartItem) {
  78.             $cartItems[$cartItem->getProductId()] = $cartItem->getCount();
  79.         }
  80.         $params['cartItems'] = $cartItems;
  81.         $params['favoriteIds'] = (new GetFavoriteIdsAction())($customer);
  82.         return $this->render('products-detail.html.twig', $params);
  83.     }
  84.     /**
  85.      * @Route("/producten/", name="shop-category-clean")
  86.      * @Route("/producten/{categoryname}~c{category}", name="shop-category", requirements={"categoryname"="[\w-]+", "category"="\d+"})
  87.      *
  88.      * @param Request $request
  89.      * @param HeadTitle $headTitleHelper
  90.      * @param BreadcrumbHelperService $breadcrumbHelperService
  91.      * @param Factory $ecommerceFactory
  92.      * //@param SegmentTrackingHelperService $segmentTrackingHelperService
  93.      * @param ListHelper $listHelper
  94.      *
  95.      * @return Response
  96.      */
  97.     public function listingAction(
  98.         Request $request,
  99.         HeadTitle $headTitleHelper,
  100.         BreadcrumbHelperService $breadcrumbHelperService,
  101.         Factory $ecommerceFactory,
  102.         //SegmentTrackingHelperService $segmentTrackingHelperService,
  103.         ListHelper $listHelper,
  104.         PaginatorInterface $paginator,
  105.         ProductSearchQueryApplier $productSearchQueryApplier
  106.     ) {
  107.         if ($this->isGranted('ROLE_REPRESENTATIVE')) {
  108.             return $this->redirectToRoute('representatives-clients');
  109.         }
  110.         $params = array_merge($request->query->all(), $request->attributes->all());
  111.         // Get product list from Index Service
  112.         $indexService = $ecommerceFactory->getIndexService();
  113.         $productListing = $indexService->getProductListForCurrentTenant();
  114.         // Check for category from URL
  115.         $category = null;
  116.         if (isset($params['category'])) {
  117.             $category = Category::getById($params['category']) ?? null;
  118.             if (!$category) {
  119.                 throw new NotFoundHttpException('Categorie niet gevonden.');
  120.             }
  121.             $params['category'] = $category;
  122.         }
  123.         // Abort product index if necessary for category list
  124.         if ($category && $parent_category = $category->getParent()) {
  125.             if ($parent_category->getType() == 'folder') {
  126.                 $breadcrumbHelperService->enrichCategoryPage($category);
  127.                 $template_file = 'products-cat.html.twig';
  128.                 return $this->render($template_file, $params);
  129.             }
  130.         }
  131.         // Else continue for filtering
  132.         if ($category) {
  133.             $productListing->setCategory($category);
  134.             $breadcrumbHelperService->enrichCategoryPage($category);
  135.         }
  136.         // Sorting
  137.         if (isset($params['sort'])) {
  138.             $productListing->setOrder('ASC');
  139.             $productListing->setOrderKey($params['sort']);
  140.         } elseif (isset($params['search']) && !empty($params['search'])) {
  141.             $db = \Pimcore\Db::get();
  142.             $escapedForLike = $productSearchQueryApplier->escapeForLike(trim((string) $params['search']));
  143.             $startsWith = $db->quote($escapedForLike . '%');
  144.             $wordStart = $db->quote('% ' . $escapedForLike . '%');
  145.             $productListing->setOrder('ASC');
  146.             $productListing->setOrderKey('CASE WHEN title LIKE ' . $startsWith . ' THEN 0 WHEN title LIKE ' . $wordStart . ' THEN 1 ELSE 2 END, title');
  147.         } else {
  148.             $productListing->setOrder('ASC');
  149.             $productListing->setOrderKey('`group`');
  150.         }
  151.         // Search
  152.         if (isset($params['search']) && !empty($params['search'])) {
  153.             $productSearchQueryApplier->apply($productListing, (string) $params['search']);
  154.             // Save the SearchInput
  155.             //            $searchInput = new SearchInput();
  156.             //            $parent = Service::createFolderByPath('/Zoekopdrachten');
  157.             //            $key = Service::getValidKey($params['search'].' '.Carbon::now().' '.microtime(), 'object');
  158.             //            $searchInput->setKey($key);
  159.             //            $searchInput->setParent($parent);
  160.             //            $searchInput->setSearchInput($params['search']);
  161.             //            $searchInput->save();
  162.         }
  163.         // Promotions only
  164.         if (isset($params['promotions']) && isset($params['promotions']) == true) {
  165.             $productListing->addCondition('promoDate1 < NOW()', 'promoDate1');
  166.             $productListing->addCondition('promoDate2 > NOW()', 'promoDate2');
  167.         }
  168.         // Stock filter
  169.         if (isset($params['stock']) && $params['stock'] == true) {
  170.             $productListing->addCondition('stock = 1', 'stock');
  171.         }
  172.         // On-order filter
  173.         if (isset($params['onorder']) && $params['onorder'] == true) {
  174.             $productListing->addCondition('onOrder = 1', 'onorder');
  175.         }
  176.         /*
  177.          * FILTERING (recent)
  178.          */
  179.         if ($request->get('recent')) {
  180.             $recentProductsIds = (new GetRecentProductsIdsAction())($this->getUser());
  181.             if (count($recentProductsIds) == 0) {
  182.                 $params['noResult'] = true;
  183.             } else {
  184.                 // Only show favorites
  185.                 $productListing->addCondition('o_id in (' . implode(',', $recentProductsIds) . ')', 'o_id');
  186.             }
  187.         }
  188.         /*
  189.          *  FILTERING (favorites)
  190.          */
  191.         /** @var Customer $customer */
  192.         $customer = $this->getUser();
  193.         // Favorite lists
  194.         $params['favoriteLists'] = (new getFavoriteListsAction())($customer);
  195.         // Get active favorite list ids
  196.         $list_ids = $request->get('favoritesList');
  197.         $params['activeFavoriteLists'] = $list_ids;
  198.         if ($params['activeFavoriteLists']) {
  199.             // Favorite Ids
  200.             $params['favoriteIds'] = (new GetFavoriteIdsAction())($customer, $list_ids);
  201.             // None found --> pass to template
  202.             if (count($params['favoriteIds']) == 0) {
  203.                 $params['noResult'] = true;
  204.             } else {
  205.                 // Only show favorites
  206.                 $productListing->addCondition('o_id in (' . implode(',', $params['favoriteIds']) . ')', 'o_id');
  207.             }
  208.         }
  209.         $params['productListing'] = $productListing;
  210.         // Filterservice/list
  211.         if ($request->get('filterdefinition') instanceof FilterDefinition) {
  212.             $filterDefinition = $request->get('filterdefinition');
  213.         }
  214.         if (empty($filterDefinition)) {
  215.             //dd(Config::getWebsiteConfig()['fallbackFilterdefinition']);
  216.             $filterDefinition = Config::getWebsiteConfig()['fallbackFilterdefinition'];
  217.         }
  218.         $filterService = $ecommerceFactory->getFilterService();
  219.         $listHelper->setupProductList($filterDefinition, $productListing, $params, $filterService, true);
  220.         $params['filterService'] = $filterService;
  221.         $params['filterDefinition'] = $filterDefinition;
  222.         /** @var ?Customer $customer */
  223.         $customer = $this->getUser();
  224.         $params['favoriteIds'] = (new GetFavoriteIdsAction())($customer);
  225.         // Update user preferences
  226.         // Update items per page
  227.         if (isset($customer)) {
  228.             if ($request->get('perpage')) {
  229.                 if ($request->get('perpage') !== $customer->getProductsPerPage()) {
  230.                     $customer->setProductsPerPage($request->get('perpage'));
  231.                     $customer->save();
  232.                 }
  233.             } elseif ($customer->getProductsPerPage() === null) {
  234.                 $customer->setProductsPerPage($filterDefinition->getPageLimit());
  235.                 $customer->save();
  236.             }
  237.             $params['productsPerPage'] = $customer->getProductsPerPage();
  238.         } else {
  239.             $params['productsPerPage'] = isset($params['perpage']) ? $params['perpage'] : $filterDefinition->getPageLimit();
  240.         }
  241.         // Update view
  242.         if (isset($customer)) {
  243.             if ($request->get('view')) {
  244.                 if ($request->get('view') !== $customer->getView()) {
  245.                     $customer->setView($request->get('view'));
  246.                     $customer->save();
  247.                 }
  248.             }
  249.             $params['view'] = $customer->getView();
  250.         } else {
  251.             $params['view'] = $params['view'] ?? '';
  252.         }
  253.         /** @var SlidingPagination $paginator */
  254.         // init pagination
  255.         $paginator = $paginator->paginate(
  256.             $productListing,
  257.             $request->get('page', 1),
  258.             isset($params['productsPerPage']) ? $params['productsPerPage'] : $filterDefinition->getPageLimit()
  259.         );
  260.         $params['results'] = $paginator;
  261.         /*
  262.          * CartItems
  263.          */
  264.         $cart = (new GetCurrentCartAction())($customer);
  265.         $cartItems = [];
  266.         foreach ($cart->getItems() as $cartItem) {
  267.             $cartItems[$cartItem->getProductId()] = $cartItem->getCount();
  268.         }
  269.         $params['cartItems'] = $cartItems;
  270.         $params['paginationVariables'] = $paginator->getPaginationData();
  271.         // Switch view based on param
  272.         $template_file = 'products-list.html.twig';
  273.         if (isset($params['view']) && $params['view'] == 'thumb') {
  274.             $template_file = 'products.html.twig';
  275.         } elseif (isset($params['view']) && $params['view'] == 'thumblist') {
  276.             $template_file = 'products-list-thumbnail.html.twig';
  277.         }
  278.         return $this->render($template_file, $params);
  279.     }
  280. }