<?php
namespace App\Ecommerce\Controller;
use App\Helpers\HelperFunctions;
use CoreShop\Bundle\OrderBundle\DTO\AddToCartInterface;
use CoreShop\Bundle\OrderBundle\Form\Type\AddToCartType;
use CoreShop\Bundle\OrderBundle\Form\Type\CartType;
use CoreShop\Component\Order\Model\PurchasableInterface;
use CoreShop\Component\Tracking\Tracker\TrackerInterface;
use Exception;
use Pimcore\Model\DataObject\CoreShopCustomer;
use Pimcore\Model\DataObject\CoreShopOrderItem;
use Pimcore\Model\Site;
use Pimcore\Twig\Extension\Templating\Placeholder;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use CoreShop\Bundle\FrontendBundle\Controller\CartController as BaseCartController;
class CartController extends BaseCartController
{
public function __construct(protected Placeholder $placeholder)
{
if (Site::isSiteRequest()) {
throw $this->createNotFoundException('Page not found!');
}
}
protected function mustLogin(bool $ajax = false): Response
{
if ($ajax) {
return new JsonResponse(['success' => false]);
}
$this->addFlash('warning', 'Kérlek jelentkezz be a kosár használatához!');
return $this->redirectToRoute('profil');
}
public function summaryAction(Request $request): Response
{
if (!$this->getUser()) {
return $this->mustLogin();
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Kosár',
'path' => $this->generateUrl('coreshop_checkout', ['stepIdentifier' => 'customer'])
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
$this->checkFixCart();
return parent::summaryAction($request);
}
public function addItemAction(Request $request): Response
{
if (!$this->getUser()) {
return $this->mustLogin($request->isXmlHttpRequest());
}
$this->denyAccessUnlessGranted('CORESHOP_CART');
$this->denyAccessUnlessGranted('CORESHOP_CART_ADD_ITEM');
$redirect = $this->getParameterFromRequest($request, '_redirect', $this->generateUrl('coreshop_index'));
$product = $this->get('coreshop.repository.stack.purchasable')->find($this->getParameterFromRequest($request, 'product'));
if (!$product instanceof PurchasableInterface) {
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
]);
}
return $this->redirect($redirect);
}
$cartItem = $this->get('coreshop.factory.order_item')->createWithPurchasable($product);
$this->getQuantityModifer()->modify($cartItem, 1);
$addToCart = $this->createAddToCart($this->getCart(), $cartItem);
$form = $this->get('form.factory')->createNamed('coreshop-' . $product->getId(), AddToCartType::class, $addToCart);
if ($request->isMethod('POST')) {
$redirect = $this->getParameterFromRequest($request, '_redirect', $this->generateUrl('coreshop_cart_summary'));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/**
* @var AddToCartInterface $addToCart
*/
$addToCart = $form->getData();
$this->getCartModifier()->addToList($addToCart->getCart(), $addToCart->getCartItem());
$this->getCartManager()->persistCart($this->getCart());
$this->get(TrackerInterface::class)->trackCartAdd(
$addToCart->getCart(),
$addToCart->getCartItem()->getProduct(),
$addToCart->getCartItem()->getQuantity(),
);
$this->addFlash('success', $this->get('translator')->trans('coreshop.ui.item_added'));
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => true,
]);
}
return $this->redirect($redirect);
}
foreach ($form->getErrors(true, true) as $error) {
$this->addFlash('error', $error->getMessage());
}
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
'errors' => array_map(function (FormError $error) {
return $error->getMessage();
}, iterator_to_array($form->getErrors(true))),
]);
}
return $this->redirect($redirect);
}
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
]);
}
return $this->render(
$this->getParameterFromRequest($request, 'template', $this->templateConfigurator->findTemplate('Product/_addToCart.html')),
[
'form' => $form->createView(),
'product' => $product,
'_redirect' => $redirect
],
);
}
/**
* @Route("/cart-add-item", name="cart_add_item", methods={"POST"})
*/
public function cartAddItemAction(Request $request): Response
{
if (!$this->getUser()) {
return $this->mustLogin($request->isXmlHttpRequest());
}
$id = (int)$request->request->get('id');
if (!$id) {
return $this->errorResponse();
}
$this->denyAccessUnlessGranted('CORESHOP_CART');
$this->denyAccessUnlessGranted('CORESHOP_CART_ADD_ITEM');
$product = $this->get('coreshop.repository.stack.purchasable')->find($id);
if (!$product instanceof PurchasableInterface) {
return $this->errorResponse();
}
$this->checkFixCart();
$cartItem = $this->get('coreshop.factory.order_item')->createWithPurchasable($product);
$this->getQuantityModifer()->modify($cartItem, 1);
$addToCart = $this->createAddToCart($this->getCart(), $cartItem);
$this->getCartModifier()->addToList($addToCart->getCart(), $addToCart->getCartItem());
try {
$this->getCartManager()->persistCart($this->getCart());
} catch (Exception $e) {
return new JsonResponse('error');
}
$this->get(TrackerInterface::class)->trackCartAdd(
$addToCart->getCart(),
$addToCart->getCartItem()->getProduct(),
$addToCart->getCartItem()->getQuantity(),
);
return $this->successResponse($request);
}
/**
* @Route("/cart-remove-item", name="cart_remove_item", methods={"POST"})
*/
public function cartRemoveItemAction(Request $request): Response
{
if (!$this->getUser()) {
return $this->mustLogin($request->isXmlHttpRequest());
}
$id = (int)$request->request->get('id');
try {
$cartItem = $this->getRemoveItem($id);
} catch (Exception $e) {
return $this->errorResponse();
}
if ($cartItem->getQuantity() <= 1) {
return $this->cartDeleteItemAction($request, $cartItem);
}
$product = $this->get('coreshop.repository.stack.purchasable')->find($id);
if (!$product instanceof PurchasableInterface) {
return $this->errorResponse();
}
$this->checkFixCart();
$cartItem = $this->get('coreshop.factory.order_item')->createWithPurchasable($product);
$cartItem->setQuantity(-1);
$addToCart = $this->createAddToCart($this->getCart(), $cartItem);
$this->getCartModifier()->addToList($addToCart->getCart(), $addToCart->getCartItem());
$this->getCartManager()->persistCart($this->getCart());
$this->get(TrackerInterface::class)->trackCartRemove(
$addToCart->getCart(),
$addToCart->getCartItem()->getProduct(),
$addToCart->getCartItem()->getQuantity(),
);
return $this->successResponse($request);
}
/**
* @Route("/cart-delete-item", name="cart_delete_item", methods={"POST"})
*/
public function cartDeleteItemAction(Request $request, ?CoreShopOrderItem $cartItem = null): Response
{
if (!$this->getUser()) {
return $this->mustLogin($request->isXmlHttpRequest());
}
if (!$cartItem instanceof CoreShopOrderItem) {
try {
$cartItem = $this->getRemoveItem((int)$request->request->get('id'));
} catch (Exception $e) {
return $this->errorResponse();
}
}
$this->checkFixCart();
$this->getCartModifier()->removeFromList($this->getCart(), $cartItem);
$this->getCartManager()->persistCart($this->getCart());
$this->get(TrackerInterface::class)->trackCartRemove($this->getCart(), $cartItem->getProduct(), $cartItem->getQuantity());
$data = [];
if (filter_var($request->request->get('fromCheckoutPage', false), FILTER_VALIDATE_BOOLEAN)) {
$data['cart'] = $this->render('seikoboutique/templates/bundles/CoreShopFrontendBundle/Cart/Summary/_checkout_cart_table.html.twig', [
'cart' => $this->getCart(),
'form' => $this->get('form.factory')->createNamed('coreshop', CartType::class, $this->getCart())->createView()
])->getContent();
}
return $this->successResponse($request, $data);
}
private function errorResponse(): JsonResponse
{
return new JsonResponse(['success' => false]);
}
private function successResponse(Request $request, array $data = []): JsonResponse
{
$count = 0;
if ($this->getCart()->getItems()) {
foreach ($this->getCart()->getItems() as $item) {
$count += $item->getQuantity();
}
}
return new JsonResponse([
'success' => true,
'count' => (int)$count,
'miniCart' => $this->miniCartAction($request)->getContent(),
...$data
]);
}
/**
* @throws Exception
*/
private function getRemoveItem($id): CoreShopOrderItem
{
if (!$id) {
throw new Exception('error');
}
$this->denyAccessUnlessGranted('CORESHOP_CART');
$this->denyAccessUnlessGranted('CORESHOP_CART_REMOVE_ITEM');
foreach ($this->getCart()->getItems() as $item) {
if ($item->getProduct()->getId() === $id) {
return $item;
}
}
throw new Exception('error');
}
private function checkFixCart(): void
{
HelperFunctions::checkFixCart($this->getCart(), $this->container);
}
public function miniCartAction(): Response
{
return $this->render($this->templateConfigurator->findTemplate('Cart/_miniCartInner.html'), [
'cart' => $this->getCart(),
]);
}
}