<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\EventSubscriber;
use App\Entity\Comment;
use App\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
/**
* Notifies post's author about new comments.
*
* @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
*/
class CommentNotificationSubscriber implements EventSubscriberInterface
{
private $mailer;
private $translator;
private $urlGenerator;
private $sender;
public function __construct(MailerInterface $mailer, UrlGeneratorInterface $urlGenerator, TranslatorInterface $translator, $sender)
{
$this->mailer = $mailer;
$this->urlGenerator = $urlGenerator;
$this->translator = $translator;
$this->sender = $sender;
}
public static function getSubscribedEvents(): array
{
return [
Events::COMMENT_CREATED => 'onCommentCreated',
];
}
public function onCommentCreated(GenericEvent $event): void
{
/** @var Comment $comment */
$comment = $event->getSubject();
$post = $comment->getPost();
$linkToPost = $this->urlGenerator->generate('blog_post', [
'slug' => $post->getSlug(),
'_fragment' => 'comment_'.$comment->getId(),
], UrlGeneratorInterface::ABSOLUTE_URL);
$subject = $this->translator->trans('notification.comment_created');
$body = $this->translator->trans('notification.comment_created.description', [
'%title%' => $post->getTitle(),
'%link%' => $linkToPost,
]);
// See https://symfony.com/doc/current/mailer.html
$message = (new Email())
->subject($subject)
->to($post->getAuthor()->getEmail())
->from($this->sender)
->html($body)
;
$this->mailer->send($message);
}
}