<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\Checkout\EventSubscriber;
use Ibexa\Checkout\Exception\NotFoundException;
use Ibexa\Contracts\Cart\Event\AddEntryEvent;
use Ibexa\Contracts\Cart\Event\MergeCartsEvent;
use Ibexa\Contracts\Cart\Event\RemoveEntryEvent;
use Ibexa\Contracts\Cart\Value\CartInterface;
use Ibexa\Contracts\Checkout\CheckoutServiceInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class CheckoutWorkflowInitializeStepSubscriber implements EventSubscriberInterface
{
private CheckoutServiceInterface $checkoutService;
private string $checkoutName;
private string $initializeStep;
public function __construct(
CheckoutServiceInterface $checkoutService,
string $checkoutName,
string $initializeStep
) {
$this->checkoutService = $checkoutService;
$this->checkoutName = $checkoutName;
$this->initializeStep = $initializeStep;
}
public static function getSubscribedEvents(): array
{
return [
AddEntryEvent::class => ['onAddEntry', -100],
RemoveEntryEvent::class => ['onRemoveEntry', -100],
MergeCartsEvent::class => ['onMergeCarts', -100],
];
}
public function onAddEntry(AddEntryEvent $event): void
{
$this->goToInitializeStep($event->getCartResult());
}
public function onRemoveEntry(RemoveEntryEvent $event): void
{
$this->goToInitializeStep($event->getCartResult());
}
public function onMergeCarts(MergeCartsEvent $event): void
{
$this->goToInitializeStep($event->getResultCart());
}
private function goToInitializeStep(CartInterface $cart): void
{
try {
$checkout = $this->checkoutService->getCheckoutForCart($cart);
} catch (NotFoundException $exception) {
return;
}
if ($this->checkoutName !== $checkout->getCheckoutName()) {
return;
}
$this->checkoutService->updateCheckout(
$checkout,
$this->checkoutService->newCheckoutUpdateStruct(
$this->initializeStep,
$checkout->getContext()->toArray()
)
);
}
}