<?php
namespace App\EventSubscriber;
use App\Service\TelegramProvider;
use Longman\TelegramBot\Exception\TelegramException;
use MLDev\FormBundle\Event\FormConfirmSuccessEvent;
use MLDev\FormBundle\Service\FormProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use MLDev\OrderBundle\Event\Notification;
use Twig\Environment;
class TelegramNotificationSubscriber implements EventSubscriberInterface
{
/**
* @var string
*/
private $chatId;
/**
* @var bool
*/
private $enable;
/**
* @var TelegramProvider
*/
private $telegramProvider;
/**
* @var FormProvider
*/
private $formProvider;
/**
* @var Environment
*/
private $templating;
/**
* TelegramNotificationSubscriber constructor.
*
* @param bool $enable
* @param string $chatId
* @param FormProvider $formProvider
* @param TelegramProvider $telegramProvider
* @param Environment $twig
*/
public function __construct(
bool $enable,
string $chatId,
FormProvider $formProvider,
TelegramProvider $telegramProvider,
Environment $twig
) {
$this->enable = $enable;
$this->chatId = $chatId;
$this->templating = $twig;
$this->formProvider = $formProvider;
$this->telegramProvider = $telegramProvider;
}
public function orderNotificationAfterHandler(Notification $event)
{
if (!$this->enable) {
return;
}
$order = $event->getOrder();
$clientInfo = $order->getInfo();
try {
$this->telegramProvider->sendMessage([
'chat_id' => $this->chatId,
'text' => $this->templating->render(
'telegram_notification/order_notification.html.twig', [
'id' => $order->getId(),
'clientInfo' => $clientInfo,
'paymentInfo' => $order->getPayment(),
'deliveryInfo' => $order->getDelivery(),
'orderCost' => $order->getOrderCost(),
'orderCostOld' => $order->getOrderCost(false),
'orderItems' => $order->getOrderItems(),
'promocodeAds' => $order->getPromocodeAds()
]
),
]);
} catch (TelegramException $e) {
}
}
public function formConfirmSuccessHandler(FormConfirmSuccessEvent $event)
{
if (!$this->enable) {
return;
}
$data = $event->getData();
$name = $event->getName();
list('settings' => $settings) = $this->formProvider->getFormConfigByName($name);
try {
$this->telegramProvider->sendMessage([
'chat_id' => $this->chatId,
'text' => $this->templating->render(
'telegram_notification/form_confirm_success.html.twig', [
'subject' => $settings['subject'] ?? 'unknown',
'formData' => $data,
]
),
]);
} catch (TelegramException $e) {
}
}
public static function getSubscribedEvents(): array
{
return [
// 'mldev.order.notification.after' => 'orderNotificationAfterHandler',
FormConfirmSuccessEvent::EVENT_NAME => 'formConfirmSuccessHandler'
];
}
}