src/EventSubscriber/CommentNotificationSubscriber.php line 43

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.     public function __construct(
  25.         private MailerInterface $mailer,
  26.         private UrlGeneratorInterface $urlGenerator,
  27.         private TranslatorInterface $translator,
  28.         private string $sender
  29.     ) {
  30.     }
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             CommentCreatedEvent::class => 'onCommentCreated',
  35.         ];
  36.     }
  37.     public function onCommentCreated(CommentCreatedEvent $event): void
  38.     {
  39.         $comment $event->getComment();
  40.         $post $comment->getPost();
  41.         $linkToPost $this->urlGenerator->generate('blog_post', [
  42.             'slug' => $post->getSlug(),
  43.             '_fragment' => 'comment_'.$comment->getId(),
  44.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  45.         $subject $this->translator->trans('notification.comment_created');
  46.         $body $this->translator->trans('notification.comment_created.description', [
  47.             'title' => $post->getTitle(),
  48.             'link' => $linkToPost,
  49.         ]);
  50.         // See https://symfony.com/doc/current/mailer.html
  51.         $email = (new Email())
  52.             ->from($this->sender)
  53.             ->to($post->getAuthor()->getEmail())
  54.             ->subject($subject)
  55.             ->html($body)
  56.         ;
  57.         // In config/packages/dev/mailer.yaml the delivery of messages is disabled.
  58.         // That's why in the development environment you won't actually receive any email.
  59.         // However, you can inspect the contents of those unsent emails using the debug toolbar.
  60.         $this->mailer->send($email);
  61.     }
  62. }