<?php
declare(strict_types=1);
namespace Ecocode\Trustpilot\Frontend\Event;
use Ecocode\Trustpilot\Model\Message\InitiateInvitationMessage;
use Ecocode\Trustpilot\Service\TrustpilotConfigurationService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\Event\OrderStateMachineStateChangeEvent;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Contracts\EventDispatcher\Event;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
/**
* @var TrustpilotConfigurationService
*/
protected $configurationService;
/**
* @var MessageBusInterface
*/
private $messageBus;
public function __construct(MessageBusInterface $messageBus, TrustpilotConfigurationService $configurationService)
{
$this->messageBus = $messageBus;
$this->configurationService = $configurationService;
}
/** @codeCoverageIgnore
* @return array<string,string>
*/
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'orderEvent',
'state_enter.order_delivery.state.shipped' => 'orderEvent',
'state_enter.order.state.completed' => 'orderEvent'
];
}
/**
* @param CheckoutOrderPlacedEvent|OrderStateMachineStateChangeEvent $event
*/
public function orderEvent(Event $event): void
{
$salesChannelId = $event->getSalesChannelId();
if (!$this->configurationService->isConfigured()) {
return;
}
if (!$this->configurationService->isInvitationSendingActive($salesChannelId)) {
return;
}
if ($event->getName() !== $this->configurationService->getSubscribedInvitationEvent($salesChannelId)) {
return;
}
$this->createOrderMessage($event->getOrder(), $event->getContext());
}
private function createOrderMessage(OrderEntity $order, Context $context): void
{
$evaluationInvitationMessage = new InitiateInvitationMessage();
$evaluationInvitationMessage
->setOrderIds([$order->getId()])
->withContext($context);
$this->messageBus->dispatch($evaluationInvitationMessage);
}
}