<?php declare(strict_types=1);
namespace Webkul\Abandoned\Subscriber;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class AbandonedCartEventSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
protected $cartNotificationRepository;
/**
* @var EntityRepositoryInterface
*/
protected $orderCustomerRepository;
public function __construct(EntityRepositoryInterface $cartNotificationRepository, EntityRepositoryInterface $orderCustomerRepository)
{
$this->cartNotificationRepository = $cartNotificationRepository;
$this->orderCustomerRepository = $orderCustomerRepository;
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'updateAbandonedCart'
];
}
public function updateAbandonedCart(EntityWrittenEvent $event)
{
$results = $event->getWriteResults();
if ($results) {
foreach ($results as $result) {
$payload = $result->getPayload();
$this->removeLastNotified($payload['id']);
}
}
}
private function removeLastNotified($orderId): void
{
$orderCustomerEntitites = $this->orderCustomerRepository->search(
(new Criteria())->addFilter(new EqualsFilter('orderId', $orderId)),
Context::createDefaultContext()
);
if ($orderCustomerEntitites->getTotal()) {
$customerId = $orderCustomerEntitites->first()->getCustomerId();
$notificationEntities = $this->cartNotificationRepository->search(
(new Criteria())->addFilter(new EqualsFilter('customerId', $customerId)),
Context::createDefaultContext()
);
if ($notificationEntities->getTotal() > 0) {
$id = $notificationEntities->first()->getId();
$this->cartNotificationRepository->delete([['id' => $id]], Context::createDefaultContext());
}
}
}
}