<?php
declare(strict_types=1);
namespace App\Module\Checkout\Subscriber;
use App\Module\Checkout\Provider\DeniosCustomerProviderInterface;
use App\Module\ShortSimpleCheckout\Event\View\FinishDispatchEvent;
use App\Module\ShortSimpleCheckout\Events;
use Commercetools\Core\Model\Order\Order;
use Denios\Data\Customer\AnonymousCustomerOrderData;
use JsonException;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @package App\Module\Checkout\Subscriber
*/
class FinishSubscriber implements EventSubscriberInterface
{
private DeniosCustomerProviderInterface $customerProvider;
/**
* @param DeniosCustomerProviderInterface $customerProvider
*/
public function __construct(
DeniosCustomerProviderInterface $customerProvider
) {
$this->customerProvider = $customerProvider;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
Events::FINISH_INDEX_DISPATCH => 'addCustomerToView'
];
}
/**
* @param FinishDispatchEvent $event
* @return void
*/
public function addCustomerToView(FinishDispatchEvent $event): void
{
$anonymousCustomerOrderData = $this->getAnonymousCustomerOrderData($event->getOrder());
$event->replaceVariable('customer', $this->customerProvider->getCustomer($anonymousCustomerOrderData));
}
/**
* @param Order $order
* @return AnonymousCustomerOrderData|null
* @throws JsonException
*/
private function getAnonymousCustomerOrderData(Order $order): ?AnonymousCustomerOrderData
{
$custom = $order->getCustom();
if ($custom === null) {
throw new RuntimeException('$custom is unexpected NULL.');
}
$fields = $custom->getFields();
if ($fields === null) {
throw new RuntimeException('$fields is unexpected NULL.');
}
if (!$fields->hasField('anonymousData')) {
return null;
}
return AnonymousCustomerOrderData::fromJson($fields->getFieldAsString('anonymousData'));
}
}