<?php declare(strict_types = 1);
namespace Zeobv\GetNotified\Storefront\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Zeobv\GetNotified\Service\MailService;
use Zeobv\GetNotified\Service\ConfigService;
/**
* Class NotificationSubscriber
*
* @package Zeobv\GetNotified\Storefront\Subscriber
*/
class NotificationSubscriber implements EventSubscriberInterface
{
/**
* @var ConfigService
*/
protected $configService;
/**
* @var MailService
*/
protected $mailService;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* NotificationSubscriber constructor.
*
* @param ConfigService $configService
* @param MailService $mailService
* @param LoggerInterface $logger
*/
public function __construct(
ConfigService $configService,
MailService $mailService,
LoggerInterface $logger
) {
$this->configService = $configService;
$this->mailService = $mailService;
$this->logger = $logger;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'zeo_stock_subscriber_product.written' => 'onNewStockSubscriber',
];
}
public function onNewStockSubscriber(EntityWrittenEvent $event): void
{
/** @var SalesChannelApiSource|mixed $source */
$source = $event->getContext()->getSource();
if (!$event->getContext()->getSource() instanceof SalesChannelApiSource) {
return;
}
$scId = $source->getSalesChannelId();
if (!$this->configService->getReceiveNotificationEmailOnNewSubscription($scId)) {
return;
}
$notificationEmail = $this->configService->getNotificationEmail($scId);
if (empty($notificationEmail)) {
return;
}
/** @var EntityWriteResult $writeResult */
foreach ($event->getWriteResults() as $writeResult) {
if ($writeResult->getOperation() !== EntityWriteResult::OPERATION_INSERT) {
continue;
}
$payload = $writeResult->getPayload();
if (!is_array($payload) || !key_exists('stockSubscriberId', $payload)) {
continue;
}
try {
$this->mailService->sendNewSubscriptionMail($notificationEmail, $payload, $event->getContext());
} catch (\Throwable $e) {
$this->logger->critical($e->getMessage(), ['trace' => $e->getTrace()]);
}
}
}
}