<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Enterprise License (PEL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PEL
*/
namespace App\Controller;
use App\Ecommerce\CartManager\GetCurrentCartAction;
use App\Ecommerce\Favorites\GetFavoriteIdsAction;
use App\Ecommerce\Favorites\GetFavoriteListsAction;
use App\Ecommerce\IndexService\ProductSearchQueryApplier;
use App\Ecommerce\RecentProducts\Action\GetRecentProductsIdsAction;
use App\Model\DataObject\Customer;
use App\Model\Product\AbstractProduct;
use App\Model\Product\Category;
use App\Website\Navigation\BreadcrumbHelperService;
use App\Website\LinkGenerator\ProductLinkGenerator;
use Carbon\Carbon;
use Knp\Component\Pager\PaginatorInterface;
use Pimcore\Config;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\FilterDefinition;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\DefaultMysql;
use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ElasticSearch\AbstractElasticSearch;
use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface;
use Pimcore\Model\DataObject\SearchInput;
use Pimcore\Model\DataObject\Service;
use Pimcore\Twig\Extension\Templating\HeadTitle;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ProductController extends BaseController
{
/**
* @Route("/product/{productname}~p{product}", name="shop-detail", requirements={"productname"="[\w-]+", "product"="\d+"})
* @param Request $request
* @param AbstractObject $object
* @param UrlSlug $urlSlug
*
* @return Response
*/
public function productDetailAction(
Request $request,
HeadTitle $headTitleHelper,
BreadcrumbHelperService $breadcrumbHelperService,
Factory $ecommerceFactory,
//SegmentTrackingHelperService $segmentTrackingHelperService,
AbstractProduct $product,
ProductLinkGenerator $productLinkGenerator
) {
if (
!($product)
) {
throw new NotFoundHttpException('Product not found.');
}
// Sort allergens per type
// Breadcrumbs
$breadcrumbHelperService->enrichProductDetailPage($product);
$params = ['product' => $product, 'allergens' => json_decode($product->getAllergens(), true)];
/*
* CartItems
*/
/** @var Customer $customer */
$customer = $this->getUser();
$cart = (new GetCurrentCartAction())($customer);
$cartItems = [];
foreach ($cart->getItems() as $cartItem) {
$cartItems[$cartItem->getProductId()] = $cartItem->getCount();
}
$params['cartItems'] = $cartItems;
$params['favoriteIds'] = (new GetFavoriteIdsAction())($customer);
return $this->render('products-detail.html.twig', $params);
}
/**
* @Route("/producten/", name="shop-category-clean")
* @Route("/producten/{categoryname}~c{category}", name="shop-category", requirements={"categoryname"="[\w-]+", "category"="\d+"})
*
* @param Request $request
* @param HeadTitle $headTitleHelper
* @param BreadcrumbHelperService $breadcrumbHelperService
* @param Factory $ecommerceFactory
* //@param SegmentTrackingHelperService $segmentTrackingHelperService
* @param ListHelper $listHelper
*
* @return Response
*/
public function listingAction(
Request $request,
HeadTitle $headTitleHelper,
BreadcrumbHelperService $breadcrumbHelperService,
Factory $ecommerceFactory,
//SegmentTrackingHelperService $segmentTrackingHelperService,
ListHelper $listHelper,
PaginatorInterface $paginator,
ProductSearchQueryApplier $productSearchQueryApplier
) {
if ($this->isGranted('ROLE_REPRESENTATIVE')) {
return $this->redirectToRoute('representatives-clients');
}
$params = array_merge($request->query->all(), $request->attributes->all());
// Get product list from Index Service
$indexService = $ecommerceFactory->getIndexService();
$productListing = $indexService->getProductListForCurrentTenant();
// Check for category from URL
$category = null;
if (isset($params['category'])) {
$category = Category::getById($params['category']) ?? null;
if (!$category) {
throw new NotFoundHttpException('Categorie niet gevonden.');
}
$params['category'] = $category;
}
// Abort product index if necessary for category list
if ($category && $parent_category = $category->getParent()) {
if ($parent_category->getType() == 'folder') {
$breadcrumbHelperService->enrichCategoryPage($category);
$template_file = 'products-cat.html.twig';
return $this->render($template_file, $params);
}
}
// Else continue for filtering
if ($category) {
$productListing->setCategory($category);
$breadcrumbHelperService->enrichCategoryPage($category);
}
// Sorting
if (isset($params['sort'])) {
$productListing->setOrder('ASC');
$productListing->setOrderKey($params['sort']);
} elseif (isset($params['search']) && !empty($params['search'])) {
$db = \Pimcore\Db::get();
$escapedForLike = $productSearchQueryApplier->escapeForLike(trim((string) $params['search']));
$startsWith = $db->quote($escapedForLike . '%');
$wordStart = $db->quote('% ' . $escapedForLike . '%');
$productListing->setOrder('ASC');
$productListing->setOrderKey('CASE WHEN title LIKE ' . $startsWith . ' THEN 0 WHEN title LIKE ' . $wordStart . ' THEN 1 ELSE 2 END, title');
} else {
$productListing->setOrder('ASC');
$productListing->setOrderKey('`group`');
}
// Search
if (isset($params['search']) && !empty($params['search'])) {
$productSearchQueryApplier->apply($productListing, (string) $params['search']);
// Save the SearchInput
// $searchInput = new SearchInput();
// $parent = Service::createFolderByPath('/Zoekopdrachten');
// $key = Service::getValidKey($params['search'].' '.Carbon::now().' '.microtime(), 'object');
// $searchInput->setKey($key);
// $searchInput->setParent($parent);
// $searchInput->setSearchInput($params['search']);
// $searchInput->save();
}
// Promotions only
if (isset($params['promotions']) && isset($params['promotions']) == true) {
$productListing->addCondition('promoDate1 < NOW()', 'promoDate1');
$productListing->addCondition('promoDate2 > NOW()', 'promoDate2');
}
// Stock filter
if (isset($params['stock']) && $params['stock'] == true) {
$productListing->addCondition('stock = 1', 'stock');
}
// On-order filter
if (isset($params['onorder']) && $params['onorder'] == true) {
$productListing->addCondition('onOrder = 1', 'onorder');
}
/*
* FILTERING (recent)
*/
if ($request->get('recent')) {
$recentProductsIds = (new GetRecentProductsIdsAction())($this->getUser());
if (count($recentProductsIds) == 0) {
$params['noResult'] = true;
} else {
// Only show favorites
$productListing->addCondition('o_id in (' . implode(',', $recentProductsIds) . ')', 'o_id');
}
}
/*
* FILTERING (favorites)
*/
/** @var Customer $customer */
$customer = $this->getUser();
// Favorite lists
$params['favoriteLists'] = (new getFavoriteListsAction())($customer);
// Get active favorite list ids
$list_ids = $request->get('favoritesList');
$params['activeFavoriteLists'] = $list_ids;
if ($params['activeFavoriteLists']) {
// Favorite Ids
$params['favoriteIds'] = (new GetFavoriteIdsAction())($customer, $list_ids);
// None found --> pass to template
if (count($params['favoriteIds']) == 0) {
$params['noResult'] = true;
} else {
// Only show favorites
$productListing->addCondition('o_id in (' . implode(',', $params['favoriteIds']) . ')', 'o_id');
}
}
$params['productListing'] = $productListing;
// Filterservice/list
if ($request->get('filterdefinition') instanceof FilterDefinition) {
$filterDefinition = $request->get('filterdefinition');
}
if (empty($filterDefinition)) {
//dd(Config::getWebsiteConfig()['fallbackFilterdefinition']);
$filterDefinition = Config::getWebsiteConfig()['fallbackFilterdefinition'];
}
$filterService = $ecommerceFactory->getFilterService();
$listHelper->setupProductList($filterDefinition, $productListing, $params, $filterService, true);
$params['filterService'] = $filterService;
$params['filterDefinition'] = $filterDefinition;
/** @var ?Customer $customer */
$customer = $this->getUser();
$params['favoriteIds'] = (new GetFavoriteIdsAction())($customer);
// Update user preferences
// Update items per page
if (isset($customer)) {
if ($request->get('perpage')) {
if ($request->get('perpage') !== $customer->getProductsPerPage()) {
$customer->setProductsPerPage($request->get('perpage'));
$customer->save();
}
} elseif ($customer->getProductsPerPage() === null) {
$customer->setProductsPerPage($filterDefinition->getPageLimit());
$customer->save();
}
$params['productsPerPage'] = $customer->getProductsPerPage();
} else {
$params['productsPerPage'] = isset($params['perpage']) ? $params['perpage'] : $filterDefinition->getPageLimit();
}
// Update view
if (isset($customer)) {
if ($request->get('view')) {
if ($request->get('view') !== $customer->getView()) {
$customer->setView($request->get('view'));
$customer->save();
}
}
$params['view'] = $customer->getView();
} else {
$params['view'] = $params['view'] ?? '';
}
/** @var SlidingPagination $paginator */
// init pagination
$paginator = $paginator->paginate(
$productListing,
$request->get('page', 1),
isset($params['productsPerPage']) ? $params['productsPerPage'] : $filterDefinition->getPageLimit()
);
$params['results'] = $paginator;
/*
* CartItems
*/
$cart = (new GetCurrentCartAction())($customer);
$cartItems = [];
foreach ($cart->getItems() as $cartItem) {
$cartItems[$cartItem->getProductId()] = $cartItem->getCount();
}
$params['cartItems'] = $cartItems;
$params['paginationVariables'] = $paginator->getPaginationData();
// Switch view based on param
$template_file = 'products-list.html.twig';
if (isset($params['view']) && $params['view'] == 'thumb') {
$template_file = 'products.html.twig';
} elseif (isset($params['view']) && $params['view'] == 'thumblist') {
$template_file = 'products-list-thumbnail.html.twig';
}
return $this->render($template_file, $params);
}
}