<?php
declare(strict_types=1);
namespace App\Controller\Shop;
use App\Entity\Order\OrderItem;
use App\Entity\Product\ProductVariant;
use Brille24\SyliusTierPricePlugin\Entity\TierPrice;
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);
$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';
/** @var OrderItem $orderItem */
$orderItem = $addToCartCommand->getCartItem();
if($orderItem->getConfiguration() && $orderItem->getConfiguration()->getImageRenderingPath()){
$source_path = $orderItem->getConfiguration()->getImageRenderingPath();
}elseif($variant->getImages()->first() != false) {
$arrayImages = $variant->getProduct()->getImagesWithoutOneType()->toArray();
usort($arrayImages, function ($a,$b){
return $a->getPosition() - $b->getPosition();
});
$source_path = $arrayImages[0]->getPath();
} else {
if($variant->getProduct()->getImages()->first() != false) {
$arrayImages = $variant->getProduct()->getImagesWithoutOneType()->toArray();
usort($arrayImages, function ($a,$b){
return $a->getPosition() - $b->getPosition();
});
$source_path = $arrayImages[0]->getPath();
}
}
$cacheManager = $this->container->get('liip_imagine.cache.manager');
$path = $cacheManager->getBrowserPath(parse_url($source_path, PHP_URL_PATH), 'sylius_shop_product_large_thumbnail_inset', [], 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');
$zone = $channelContext->getChannel()->getDefaultTaxZone();
$taxResolver = $this->container->get('sylius.tax_rate_resolver');
$taxCalculator = $this->container->get('sylius.tax_calculator');
$taxRate = $taxResolver->resolve($variant, ['zone' => $zone]);
$price = $variant->getChannelPricingForChannel($channelContext->getChannel())->getPrice();
$possibleTierPrices = $this->manager->getRepository(TierPrice::class)->getSortedTierPrices($variant, $channelContext->getChannel(), null);
$cheapestTierPrice = null;
foreach ($possibleTierPrices as $tierPrice) {
if ($tierPrice->getQty() > $quantityAdd) {
break;
}
$cheapestTierPrice = $tierPrice;
}
if ($cheapestTierPrice) {
$price = $cheapestTierPrice->getPrice();
}
if ($taxRate) {
$totalTaxAmount = $taxCalculator->calculate($price, $taxRate);
$price = $price + $totalTaxAmount;
}
$priceConvert = $moneyFormatter->format((int) $price, $cart->getCurrencyCode(), $localeContext->getLocaleCode());
$responseJson = [ 'variantName' => $name,
'source_path' => $path, 'options' => $htmlOptions, 'quantity' => $quantityAdd, 'price' => $priceConvert ];
//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(),
]
);
}
}