src/EventSubscriber/CommentNotificationSubscriber.php line 50

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\Entity\Comment;
  12. use App\Events;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\EventDispatcher\GenericEvent;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use Symfony\Component\Mailer\MailerInterface;
  18. use Symfony\Component\Mime\Email;
  19. /**
  20. * Notifies post's author about new comments.
  21. *
  22. * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
  23. */
  24. class CommentNotificationSubscriber implements EventSubscriberInterface
  25. {
  26. private $mailer;
  27. private $translator;
  28. private $urlGenerator;
  29. private $sender;
  30. public function __construct(MailerInterface $mailer, UrlGeneratorInterface $urlGenerator, TranslatorInterface $translator, $sender)
  31. {
  32. $this->mailer = $mailer;
  33. $this->urlGenerator = $urlGenerator;
  34. $this->translator = $translator;
  35. $this->sender = $sender;
  36. }
  37. public static function getSubscribedEvents(): array
  38. {
  39. return [
  40. Events::COMMENT_CREATED => 'onCommentCreated',
  41. ];
  42. }
  43. public function onCommentCreated(GenericEvent $event): void
  44. {
  45. /** @var Comment $comment */
  46. $comment = $event->getSubject();
  47. $post = $comment->getPost();
  48. $linkToPost = $this->urlGenerator->generate('blog_post', [
  49. 'slug' => $post->getSlug(),
  50. '_fragment' => 'comment_'.$comment->getId(),
  51. ], UrlGeneratorInterface::ABSOLUTE_URL);
  52. $subject = $this->translator->trans('notification.comment_created');
  53. $body = $this->translator->trans('notification.comment_created.description', [
  54. '%title%' => $post->getTitle(),
  55. '%link%' => $linkToPost,
  56. ]);
  57. // See https://symfony.com/doc/current/mailer.html
  58. $message = (new Email())
  59. ->subject($subject)
  60. ->to($post->getAuthor()->getEmail())
  61. ->from($this->sender)
  62. ->html($body)
  63. ;
  64. $this->mailer->send($message);
  65. }
  66. }