src/EventSubscriber/CommentNotificationSubscriber.php line 48

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\EventSubscriber;
  11. use App\Event\CommentCreatedEvent;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\Mailer\MailerInterface;
  14. use Symfony\Component\Mime\Email;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. /**
  18.  * Notifies post's author about new comments.
  19.  *
  20.  * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
  21.  */
  22. class CommentNotificationSubscriber implements EventSubscriberInterface
  23. {
  24.     private $mailer;
  25.     private $translator;
  26.     private $urlGenerator;
  27.     private $sender;
  28.     public function __construct(MailerInterface $mailerUrlGeneratorInterface $urlGeneratorTranslatorInterface $translatorstring $sender)
  29.     {
  30.         $this->mailer $mailer;
  31.         $this->urlGenerator $urlGenerator;
  32.         $this->translator $translator;
  33.         $this->sender $sender;
  34.     }
  35.     public static function getSubscribedEvents(): array
  36.     {
  37.         return [
  38.             CommentCreatedEvent::class => 'onCommentCreated',
  39.         ];
  40.     }
  41.     public function onCommentCreated(CommentCreatedEvent $event): void
  42.     {
  43.         $comment $event->getComment();
  44.         $post $comment->getPost();
  45.         $linkToPost $this->urlGenerator->generate('blog_post', [
  46.             'slug' => $post->getSlug(),
  47.             '_fragment' => 'comment_'.$comment->getId(),
  48.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  49.         $subject $this->translator->trans('notification.comment_created');
  50.         $body $this->translator->trans('notification.comment_created.description', [
  51.             '%title%' => $post->getTitle(),
  52.             '%link%' => $linkToPost,
  53.         ]);
  54.         // See https://symfony.com/doc/current/mailer.html
  55.         $email = (new Email())
  56.             ->from($this->sender)
  57.             ->to($post->getAuthor()->getEmail())
  58.             ->subject($subject)
  59.             ->html($body)
  60.         ;
  61.         // In config/packages/dev/mailer.yaml the delivery of messages is disabled.
  62.         // That's why in the development environment you won't actually receive any email.
  63.         // However, you can inspect the contents of those unsent emails using the debug toolbar.
  64.         $this->mailer->send($email);
  65.     }
  66. }