<?php
declare(strict_types=1);
namespace NetInventors\NetiNextAccessManager\Subscriber;
use NetInventors\NetiNextAccessManager\Components\Errors\Checkout\Cart\CustomerGroupBlockedForBuyError;
use NetInventors\NetiNextAccessManager\Service\CustomerService;
use NetInventors\NetiNextAccessManager\Service\PluginConfig;
use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CartSubscriber implements EventSubscriberInterface
{
private PluginConfig $pluginConfig;
private CustomerService $customerService;
private CartService $cartService;
private EntityRepositoryInterface $productRepository;
public function __construct(
PluginConfig $pluginConfig,
CustomerService $customerService,
CartService $cartService,
EntityRepositoryInterface $productRepository
) {
$this->pluginConfig = $pluginConfig;
$this->customerService = $customerService;
$this->productRepository = $productRepository;
$this->cartService = $cartService;
}
public static function getSubscribedEvents(): array
{
return [
AfterLineItemAddedEvent::class => 'onAfterItemAdded',
];
}
public function onAfterItemAdded(AfterLineItemAddedEvent $event): void
{
if (!$this->pluginConfig->isActive() || [] === $this->pluginConfig->getGroupsForBlockedBuyButton()) {
return;
}
$salesChannelContext = $event->getSalesChannelContext();
if (!$this->customerService->isBuyButtonBlocked($salesChannelContext)) {
return;
}
$items = $event->getLineItems();
$cart = $event->getCart();
$productNames = $this->getProducts($items, $event->getContext());
/** @var LineItem $item */
foreach ($items as $item) {
$itemId = $item->getId();
$itemName = (string) ($productNames[$itemId] ?? $itemId);
$this->cartService->remove($cart, $itemId, $salesChannelContext);
$cart->addErrors(
new CustomerGroupBlockedForBuyError(
$itemId,
$itemName
)
);
}
}
private function getProducts(array $items, Context $context): array
{
$productNames = [];
$productIds = [];
/** @var LineItem $item */
foreach ($items as $item) {
$productIds[] = [ 'id' => $item->getId() ];
}
$products = $this->productRepository->search(new Criteria($productIds), $context)->getElements();
/** @var ProductEntity $product */
foreach ($products as $product) {
$productNames[$product->getId()] = $product->getName() ?? $product->getProductNumber();
}
return $productNames;
}
}