<?php
namespace Lnb\Shopware6\LnbSubscription\Subscriber\Subscription;
use Lnb\Shopware6\LnbSubscription\Entity\SubscriptionOrder\SubscriptionOrderDefinition;
use Lnb\Shopware6\LnbSubscription\Service\History\SubscriptionOrderHistoryService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SubscriptionHistorySubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly SubscriptionOrderHistoryService $subscriptionOrderHistoryService,
private readonly LoggerInterface $logger
) {
}
public static function getSubscribedEvents(): array
{
return [
SubscriptionOrderDefinition::ENTITY_NAME . '.written' => 'onSubscriptionWritten'
];
}
public function onSubscriptionWritten(EntityWrittenEvent $event): void
{
$results = $event->getWriteResults();
try {
$this->subscriptionOrderHistoryService->setUserId($event->getContext()->getSource());
foreach ($results as $result) {
if ($result->getExistence()->exists()) {
$this->subscriptionOrderHistoryService->logUpdate($result);
} else {
$this->subscriptionOrderHistoryService->logInitial($result);
}
}
$this->subscriptionOrderHistoryService->save();
} catch (\Throwable $exception) {
$this->logger->error(
sprintf('Could not create history entry for subscription. Error: %s', $exception->getMessage()),
[
'trace' => $exception->getTraceAsString(),
'eventIds' => $event->getIds()
]
);
}
}
}