<?php declare(strict_types=1);
namespace ImnxxCartRestorer\Storefront\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
use Doctrine\DBAL\Connection;
class CartRestorerSubscriber implements EventSubscriberInterface {
private CartService $cartService;
private Connection $connection;
public function __construct(CartService $cartService, Connection $connection) {
$this->cartService = $cartService;
$this->connection = $connection;
}
public static function getSubscribedEvents(): array {
return [
GenericPageLoadedEvent::class => 'onPageLoaded',
CustomerLoginEvent::class => ['onCustomerLogin'],
];
}
public function onPageLoaded(GenericPageLoadedEvent $event) {
if (isset($_GET['cartId']) && !empty($_GET['cartId'])) {
$cartOld = $this->cartService->getCart($_GET['cartId'], $event->getSalesChannelContext());
$cartCurrent = $this->cartService->getCart(
$event->getSalesChannelContext()->getToken(),
$event->getSalesChannelContext(),
);
foreach ($cartOld->getLineItems() as $lineItem) {
$this->cartService->add($cartCurrent, $lineItem, $event->getSalesChannelContext());
}
}
}
public function onCustomerLogin(CustomerLoginEvent $event) {
$customerId = $event->getCustomerId();
$latestCartTokenFromCustomer =
$this->connection
->executeQuery(
'SELECT token FROM cart WHERE customer_id = UNHEX(:customerId) ORDER BY created_at DESC LIMIT 1',
[
'customerId' => $customerId,
],
)
->fetchAllAssociative()[0]['token'] ?? null;
if ($latestCartTokenFromCustomer != null) {
$currentCart = $this->cartService->getCart(
$event->getSalesChannelContext()->getToken(),
$event->getSalesChannelContext(),
);
$lastCart = $this->cartService->getCart(
$latestCartTokenFromCustomer,
$event->getSalesChannelContext(),
);
foreach ($lastCart->getLineItems() as $lineItem) {
$this->cartService->add($currentCart, $lineItem, $event->getSalesChannelContext());
}
}
if (
isset($_COOKIE['DokumentenId_productnumber_for_login']) &&
$_COOKIE['DokumentenId_productnumber_for_login'] !== ''
) {
setcookie('docoumentIdProductNumberAfterLogin', $_COOKIE['DokumentenId_productnumber_for_login']);
unset($_COOKIE['DokumentenId_productnumber_for_login']);
}
header('Location: ' . $_SERVER['REQUEST_URI']);
die();
}
}