<?php
declare(strict_types=1);
namespace MadBodymedBundle\Subscriber;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class CartSubscriber implements EventSubscriberInterface
{
private SalesChannelRepositoryInterface $salesChannelProductRepository;
public function __construct(SalesChannelRepositoryInterface $salesChannelProductRepository)
{
$this->salesChannelProductRepository = $salesChannelProductRepository;
}
public static function getSubscribedEvents(): array
{
return [
#AfterLineItemAddedEvent::class => 'onAfterLineItemAdded',
CartConvertedEvent::class => 'onCartConverted',
#BeforeLineItemAddedEvent::class => 'onLineItemAdded',
OrderEvents::ORDER_LINE_ITEM_LOADED_EVENT => 'lineItemLoaded',
];
}
public function onLineItemAdded(BeforeLineItemAddedEvent $event) //Zum Prüfen ob der Bundle Artikel vollständig konfiguriert wurde, bevor er in den Warenkorb gelegt wurde.
{
$lineItems = $event->getCart()->getLineItems();
foreach($lineItems->getElements() as $key => $lineItem){
//Prüfen ob es ein Bundle ist
if($lineItem->getPayload()['isBundle'] === true){
foreach($lineItem->getChildren() as $lineItemChild){
dump($lineItemChild->getReferencedId());
$criteria = (new Criteria())
->addAssociation('product')
->addFilter(new EqualsFilter('id', $lineItemChild->getReferencedId()))
;
$article = $this->salesChannelProductRepository->search($criteria, $event->getSalesChannelContext())->first();
//Prüfen ob es ein Variantenartikel ist, der keinen Parent hat.
if($article->getChildCount() > 0 and $article->getParentId() == null){
return;
}
}
}
}
}
public function lineItemLoaded(EntityLoadedEvent $event){
$lineitems = $event->getEntities();
usort($lineitems, function($a, $b) {
return $a->position <=> $b->position;
});
}
public function onCartConverted(CartConvertedEvent $event)
{
$convertedCart = $event->getConvertedCart();
$newLineItems = [];
foreach ($convertedCart['lineItems'] as $key => $lineItem) {
if (isset($lineItem['payload']['isBundle']) && \boolval($lineItem['payload']['isBundle']) === true) {
$lineItem['bundle'] = 1;
/*if (isset($lineItem['payload']['bundlePriceType'])) {
$lineItem['bundlePriceType'] = $lineItem['payload']['bundlePriceType'];
}
if (isset($lineItem['payload']['nomsBundleType'])) {
$lineItem['nomsBundleType'] = $lineItem['payload']['nomsBundleType'];
}*/
}
$newLineItems[] = $lineItem;
}
$convertedCart['lineItems'] = $newLineItems;
$event->setConvertedCart($convertedCart);
}
}