<?php declare(strict_types=1);
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 03 lip 2020
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\MojeBambinoEngine\Subscriber;
use Shopware\Core\Checkout\Cart\Error\ErrorCollection;
use Shopware\Core\Checkout\Cart\Error\IncompleteLineItemError;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\Event\LineItemAddedEvent;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class LineItemAddSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
protected $productRepository;
/**
* @var Session
*/
protected $session;
protected $translator;
public function __construct(
EntityRepository $exampleRepository,
Session $session,
$translator
)
{
$this->productRepository = $exampleRepository;
$this->session = $session;
$this->translator = $translator;
}
public static function getSubscribedEvents(): array
{
return [
BeforeLineItemAddedEvent::class => 'onLineItemAdded'
];
}
public function onLineItemAdded(BeforeLineItemAddedEvent $event): void
{
$lineItem = $event->getLineItem();
$cart = $event->getCart();
$context = $event->getContext();
if ($lineItem->getType() !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
return;
}
$id = $lineItem->getReferencedId();
if (!is_string($id) || !Uuid::isValid($id)) {
return;
}
$product = $this->productRepository->search(new Criteria([$id]), $context)->getEntities()->first();
if ($product === null) {
return;
}
$customFields = $product->getCustomFields();
if (!is_array($customFields)) {
return;
}
if (
isset($customFields['crehler_product_exclude_from_cart'])
&& $customFields['crehler_product_exclude_from_cart'] === true
) {
$errorCollection = new ErrorCollection();
$errorCollection->add(new IncompleteLineItemError($lineItem->getId(), $this->translator->trans("bambino.checkout.unbuyableProduct")));
$cart->remove($lineItem->getId());
$cart->setErrors($errorCollection);
}
}
}