src/Controller/Shop/AddItemToCartController.php line 34

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Shop;
  4. use App\Entity\Channel\ChannelPricing;
  5. use App\Entity\Order\Order;
  6. use App\Entity\Product\ProductVariant;
  7. use App\Entity\Product\SimpleProductOption;
  8. use App\Entity\Product\SimpleProductOptionValue;
  9. use App\Provider\PriceTTCProvider;
  10. use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
  11. use Sylius\Bundle\OrderBundle\Controller\OrderItemController;
  12. use Sylius\Component\Order\CartActions;
  13. use Sylius\Component\Order\Model\OrderItemInterface;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Exception\HttpException;
  17. class AddItemToCartController extends OrderItemController
  18. {
  19.     public function addAction(Request $request): Response
  20.     {
  21.         /** @var Order $cart */
  22.         $cart $this->getCurrentCart();
  23.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  24.         $this->isGrantedOr403($configurationCartActions::ADD);
  25.         /** @var OrderItemInterface $orderItem */
  26.         $orderItem $this->newResourceFactory->create($configuration$this->factory);
  27.         $this->getQuantityModifier()->modify($orderItem1);
  28.         $form $this->getFormFactory()->create(
  29.             $configuration->getFormType(),
  30.             $this->createAddToCartCommand($cart$orderItem),
  31.             $configuration->getFormOptions()
  32.         );
  33.         if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
  34.             $moneyFormatter $this->container->get('sylius.money_formatter');
  35.             // récupérer toutes les options possibles
  36.             $em $this->getDoctrine()->getManager();
  37.             $simpleProductOptions $em->getRepository(SimpleProductOption::class)->findAll();
  38.             $simpleProductOptionsCodes = [];
  39.             /** @var SimpleProductOption $simpleProductOption */
  40.             foreach ($simpleProductOptions as $simpleProductOption) {
  41.                 $simpleProductOptionsCodes[] = $simpleProductOption->getCode();
  42.             }
  43.             // parcourir $request->request->all() pour voir si des éléments correspondent aux options
  44.             // si oui, on ajoute à l'orderItem l'option et l'option value
  45.             $orderItemOptions = [];
  46.             foreach ($request->request->all() as $key => $value) {
  47.                 if (in_array($key$simpleProductOptionsCodes)) {
  48.                     /** @var SimpleProductOptionValue $simpleProductOptionValue */
  49.                     $simpleProductOptionValue $em->getRepository(SimpleProductOptionValue::class)->findOneBy(['code' => $value]);
  50.                     if ($simpleProductOptionValue) {
  51.                         $orderItemOptions[$key]['code'] = $simpleProductOptionValue->getCode();
  52.                         $orderItemOptions[$key]['price'] = $simpleProductOptionValue->getPrice();
  53.                         $orderItemOptions[$key]['name'] = $simpleProductOptionValue->getTranslation($cart->getLocaleCode())->getName();
  54.                     }
  55.                 }
  56.             }
  57.             /** @var AddToCartCommandInterface $addToCartCommand */
  58.             $addToCartCommand $form->getData();
  59.             /** @var ProductVariant $variant */
  60.             $variant $addToCartCommand->getCartItem()->getVariant();
  61.             /** @var ChannelPricing $pricing */
  62.             $price $variant->getChannelPricingForChannel($cart->getChannel())->getPrice();
  63.             $totalPrice $price;
  64.             $htmlSimpleProductOptions '';
  65.             $installation false;
  66.             if (count($orderItemOptions) > 0) {
  67.                 foreach ($orderItemOptions as $orderItemOption => $orderItemOptionValue) {
  68.                     if($orderItemOption === "installation" && $orderItemOptionValue['code'] !== "no_installation" ){
  69.                         $installation true;
  70.                     }
  71.                     $totalPrice += $orderItemOptionValue['price'];
  72.                     $priceOptionConvert $moneyFormatter->format($orderItemOptionValue['price'], $cart->getCurrencyCode(), $cart->getLocaleCode());
  73.                     $htmlSimpleProductOptions .= '<div>
  74.                                  <small><strong class="visible-devis">'.$orderItemOptionValue['code'] .' : </strong>'$priceOptionConvert .'</small>
  75.                                  </div>';
  76.                 }
  77.             }
  78.             $addToCartCommand->getCartItem()->setImmutable(true);
  79.             $addToCartCommand->getCartItem()->setSimpleProductOptions($orderItemOptions);
  80.             $addToCartCommand->getCartItem()->setUnitPrice($totalPrice);
  81.             $errors $this->getCartItemErrors($addToCartCommand->getCartItem());
  82.             if (count($errors)) {
  83.                 $form $this->getAddToCartFormWithErrors($errors$form);
  84.                 return $this->handleBadAjaxRequestView($configuration$form);
  85.             }
  86.             $event $this->eventDispatcher->dispatchPreEvent(CartActions::ADD$configuration$orderItem);
  87.             if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  88.                 throw new HttpException($event->getErrorCode(), $event->getMessage());
  89.             }
  90.             if ($event->isStopped()) {
  91.                 $this->flashHelper->addFlashFromEvent($configuration$event);
  92.                 return $this->redirectHandler->redirectToIndex($configuration$orderItem);
  93.             }
  94.             $this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
  95.             $source_path '//placehold.it/400x300';
  96.             if($variant->getImages()->first() != false) {
  97.                 $source_path $variant->getImages()->first()->getPath();
  98.             }
  99.             else {
  100.                 if($variant->getProduct()->getImages()->first() != false) {
  101.                     $source_path $variant->getProduct()->getImages()->first()->getPath();
  102.                 }
  103.             }
  104.             $cacheManager $this->container->get('liip_imagine.cache.manager');
  105.             $path $cacheManager->getBrowserPath(parse_url($source_pathPHP_URL_PATH), 'sylius_shop_product_large_thumbnail', [], null);
  106.             $htmlOptions '';
  107.             foreach ($variant->getOptionValues() as $optionValue) {
  108.                 $htmlOptions .= '<div>
  109.                                  <small><strong class="visible-devis">'.$optionValue->getName() .' : </strong>'$optionValue->getValue() .'</small>
  110.                                  </div>';
  111.             }
  112.             $quantityAdd $addToCartCommand->getCartItem()->getQuantity();
  113.             if ($variant->getName() !== null) {
  114.                 $name $variant->getName();
  115.             }
  116.             else {
  117.                 $name $variant->getProduct()->getName();
  118.             }
  119.             //add tva
  120.             /** @var PriceTTCProvider $priceTTCProvider */
  121.             $priceTTCProvider $this->container->get('app.provider.price_ttc_provider');
  122.             $totalPrice $priceTTCProvider->getPriceTTCFromVariant($variant$totalPrice$installation);
  123.             $priceConvert $moneyFormatter->format((int)$totalPrice$cart->getCurrencyCode(), $cart->getLocaleCode());
  124.             //partie datalayer
  125.             $gtmEventListener $this->container->get('app.google_tag_manager.listener.event');
  126.             $datalayer $gtmEventListener->addToCart($orderItem->getProduct());
  127.             $responseJson = [
  128.                 'variantName' => $name,
  129.                 'source_path' => $path,
  130.                 'options' => $htmlOptions,
  131.                 'quantity' => $quantityAdd,
  132.                 'simpleProductOptions' => $htmlSimpleProductOptions,
  133.                 'price' => $priceConvert,
  134.                 'dataLayer' => $datalayer
  135.             ];
  136.             $cartManager $this->getCartManager();
  137.             $cartManager->persist($cart);
  138.             $cartManager->flush();
  139.             $resourceControllerEvent $this->eventDispatcher->dispatchPostEvent(CartActions::ADD$configuration$orderItem);
  140.             if ($resourceControllerEvent->hasResponse()) {
  141.                 return $resourceControllerEvent->getResponse();
  142.             }
  143.             return new Response(json_encode($responseJson));
  144.         }
  145.         if (!$configuration->isHtmlRequest()) {
  146.             return $this->handleBadAjaxRequestView($configuration$form);
  147.         }
  148.         return $this->render(
  149.             $configuration->getTemplate(CartActions::ADD '.html'),
  150.             [
  151.                 'configuration' => $configuration,
  152.                 $this->metadata->getName() => $orderItem,
  153.                 'form' => $form->createView(),
  154.             ]
  155.         );
  156.     }
  157. }