<?php
declare(strict_types=1);
namespace App\Controller\Shop;
use App\Entity\Product\ProductVariant;
use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
use Sylius\Bundle\OrderBundle\Controller\OrderItemController;
use Sylius\Component\Order\CartActions;
use Sylius\Component\Order\Model\OrderItemInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class AddItemToCartController extends OrderItemController
{
public function addAction(Request $request): Response
{
$cart = $this->getCurrentCart();
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, CartActions::ADD);
/** @var OrderItemInterface $orderItem */
$orderItem = $this->newResourceFactory->create($configuration, $this->factory);
$orderItem->setPurchasePrice($orderItem->getVariant()->getPurchasePrice());
$this->getQuantityModifier()->modify($orderItem, 1);
$form = $this->getFormFactory()->create(
$configuration->getFormType(),
$this->createAddToCartCommand($cart, $orderItem),
$configuration->getFormOptions()
);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
/** @var AddToCartCommandInterface $addToCartCommand */
$addToCartCommand = $form->getData();
$errors = $this->getCartItemErrors($addToCartCommand->getCartItem());
if (0 < count($errors)) {
$form = $this->getAddToCartFormWithErrors($errors, $form);
return $this->handleBadAjaxRequestView($configuration, $form);
}
$event = $this->eventDispatcher->dispatchPreEvent(CartActions::ADD, $configuration, $orderItem);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
}
$this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
$cartManager = $this->getCartManager();
$cartManager->persist($cart);
$cartManager->flush();
$resourceControllerEvent = $this->eventDispatcher->dispatchPostEvent(CartActions::ADD, $configuration, $orderItem);
if ($resourceControllerEvent->hasResponse()) {
return $resourceControllerEvent->getResponse();
}
/** @var ProductVariant $variant */
$variant = $addToCartCommand->getCartItem()->getVariant();
$source_path = '//placehold.it/400x300';
if ($variant->getImages()->first() != false) {
$source_path = $variant->getImages()->first()->getPath();
} else {
if ($variant->getProduct()->getImages()->first() != false) {
$source_path = $variant->getProduct()->getImages()->first()->getPath();
}
}
$cacheManager = $this->container->get('liip_imagine.cache.manager');
$path = $cacheManager->getBrowserPath(parse_url($source_path, \PHP_URL_PATH), 'sylius_shop_product_large_thumbnail', [], null);
$htmlOptions = '';
foreach ($variant->getOptionValues() as $optionValue) {
$htmlOptions .= '<div>
<small><strong class="visible-devis">' . $optionValue->getName() . ' : </strong>' . $optionValue->getValue() . '</small>
</div>';
}
$quantityAdd = $addToCartCommand->getCartItem()->getQuantity();
if ($variant->getName() !== null) {
$name = $variant->getName();
} else {
$name = $variant->getProduct()->getName();
}
$moneyFormatter = $this->container->get('sylius.money_formatter');
$localeContext = $this->container->get('sylius.context.locale');
$channelContext = $this->container->get('sylius.context.channel');
$productVariantPriceCalculator = $this->container->get('sylius.calculator.product_variant_price');
$price = $productVariantPriceCalculator->calculate($variant, ['channel' => $channelContext->getChannel(), 'quantity' => $orderItem->getQuantity(), 'customer' => $cart->getCustomer()]);
$priceConvert = $moneyFormatter->format($price, $cart->getCurrencyCode(), $localeContext->getLocaleCode());
//partie datalayer
$gtmEventListener = $this->container->get('app.google_tag_manager.listener.event');
$datalayer = $gtmEventListener->addToCart($orderItem->getProduct());
$responseJson = ['variantName' => $name,
'source_path' => $path, 'options' => $htmlOptions, 'quantity' => $quantityAdd, 'price' => $priceConvert, 'dataLayer' => $datalayer, ];
// return avec popup
return new Response(json_encode($responseJson));
}
if (!$configuration->isHtmlRequest()) {
return $this->handleBadAjaxRequestView($configuration, $form);
}
return $this->render(
$configuration->getTemplate(CartActions::ADD . '.html'),
[
'configuration' => $configuration,
$this->metadata->getName() => $orderItem,
'form' => $form->createView(),
]
);
}
}