<?php declare(strict_types=1);
namespace MasterFFL\Checkout\Subscriber;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
class OrderSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $orderRepository;
private LoggerInterface $logger;
public function __construct(
EntityRepositoryInterface $orderRepository,
LoggerInterface $logger
) {
$this->orderRepository = $orderRepository;
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'onOrderWritten'
];
}
public function onOrderWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $writeResult) {
$payload = $writeResult->getPayload();
// Check if this is an FFL order
if (isset($payload['customFields']['is_ffl_order']) && $payload['customFields']['is_ffl_order']) {
$this->handleFFLOrder($payload, $event->getContext());
}
}
}
private function handleFFLOrder(array $orderData, $context): void
{
try {
$this->logger->info('Processing FFL order', [
'orderId' => $orderData['id'],
'fflDealerId' => $orderData['customFields']['ffl_dealer_id'] ?? null
]);
// Store FFL dealer information in order custom fields
if (isset($orderData['customFields']['ffl_dealer_id'])) {
$this->updateOrderWithFFLData($orderData['id'], $orderData['customFields'], $context);
}
} catch (\Exception $e) {
$this->logger->error('Error processing FFL order', [
'orderId' => $orderData['id'],
'error' => $e->getMessage()
]);
}
}
private function updateOrderWithFFLData(string $orderId, array $customFields, $context): void
{
$this->orderRepository->update([
[
'id' => $orderId,
'customFields' => array_merge($customFields, [
'ffl_processed' => true,
'ffl_processing_date' => date('Y-m-d H:i:s')
])
]
], $context);
}
}