Skip to content
This repository has been archived by the owner on Dec 29, 2023. It is now read-only.

Commit

Permalink
Messenger: First prototype, fix #1
Browse files Browse the repository at this point in the history
  • Loading branch information
jgauthi committed Jun 11, 2023
1 parent 8d134b5 commit d7695a4
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 56 deletions.
46 changes: 18 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,9 @@

More information on [symfony website](https://symfony.com/doc/6.2/reference/requirements.html).

## Features developed
Messenger showcase.
## Messenger POC
Messenger provides a message bus with the ability to send messages and then handle them immediately in your application or send them through transports (e.g. queues) to be handled later. To learn more deeply about it, read the [Messenger component docs](https://symfony.com/doc/6.2/messenger.htmlcomponents/messenger.html).

**Current study:** Please review, edit and commit them: these files are yours.

symfony/messenger instructions:

* You're ready to use the Messenger component. You can define your own message buses
or start using the default one right now by injecting the message_bus service
or type-hinting Symfony\Component\Messenger\MessageBusInterface in your code.

* To send messages to a transport and handle them asynchronously:

1. Update the MESSENGER_TRANSPORT_DSN env var in .env if needed
and framework.messenger.transports.async in config/packages/messenger.yaml;
2. (if using Doctrine) Generate a Doctrine migration bin/console doctrine:migration:diff
and execute it bin/console doctrine:migration:migrate
3. Route your message classes to the async transport in config/packages/messenger.yaml.

* Read the documentation at https://symfony.com/doc/current/messenger.html

## Installation
Command lines:
Expand All @@ -41,24 +24,31 @@ composer install

php bin/console doctrine:database:create
php bin/console doctrine:migrations:migrate -n

# Optional
php bin/console doctrine:fixtures:load -n
```

For the asset symlink install, launch a terminal on administrator in windows environment.

## Usage
Just execute this command to run the built-in web server _(require [symfony installer](https://symfony.com/download))_ and access the application in your browser at <http://localhost:8000>:

```bash
# Dev env
# Edit "MAILER_DSN" in .env.local with SMTP service (example: mailtrap)

# Install fixtures (only for dev environnement), start server
symfony console doctrine:fixtures:load -n
symfony server:start

# Test env
APP_ENV=test php -d variables_order=EGPCS -S 127.0.0.1:8000 -t public/
# Launch Messages service
symfony console messenger:consume async
```

Alternatively, you can [configure a web server](https://symfony.com/doc/current/cookbook/configuration/web_server_configuration.html) like Nginx or Apache to run the application.
Debug commands:

```shell
php bin/console messenger:consume async -vv

# Retry failed messages several times (3 attempts)
php bin/console messenger:failed:show
php bin/console messenger:failed:retry
```

Your commit is checked by several dev tools (like phpstan, php cs fixer...). These tools were managed by [Grumphp](https://github.com/phpro/grumphp), you can edit configuration on file [grumphp.yml](./grumphp.yml) or check manually with the command: `./vendor/bin/grumphp run`.
Enjoy!
2 changes: 1 addition & 1 deletion config/packages/messenger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ framework:
routing:
# Route your messages to the transports
# 'App\Message\YourMessage': async
# App\Messenger\Message\SendNewsletterMessage: async
App\Message\SendComment: async
15 changes: 14 additions & 1 deletion src/DataFixtures/CommentFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@
namespace App\DataFixtures;

use App\Entity\{Comment, Dossier, User};
use App\Message\SendComment;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory as FakerFactory;
use Symfony\Component\Messenger\MessageBusInterface;

class CommentFixtures extends Fixture implements DependentFixtureInterface
{
public const NB_FIXTURE = 10;
private \Faker\Generator $faker;

public function __construct()
public function __construct(private MessageBusInterface $bus)
{
$this->faker = FakerFactory::create();
}
Expand All @@ -36,6 +38,17 @@ public function load(ObjectManager $manager): void
}

$manager->flush();

// Add Comments to Symfony BUS
for ($i = 0; $i < self::NB_FIXTURE; ++$i) {
/** @var Comment $comment */
$comment = $this->getReference("comment_$i");
if (empty($comment->getId())) {
continue;
}

$this->bus->dispatch(new SendComment($comment->getId()));
}
}

public function getDependencies(): array
Expand Down
11 changes: 3 additions & 8 deletions src/Message/SendComment.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@

class SendComment
{
public function __construct(private readonly int $userId, private readonly int $dossierId)
public function __construct(private readonly int $commentId)
{
}

public function getUserId(): int
public function getCommentId(): int
{
return $this->userId;
}

public function getDossierId(): int
{
return $this->dossierId;
return $this->commentId;
}
}
19 changes: 9 additions & 10 deletions src/MessageHandler/SendCommentHandler.php
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
<?php
namespace App\MessageHandler;

use App\Entity\Comment;
use App\Entity\User;
use App\Message\SendComment;
use App\Repository\CommentRepository;
use App\Service\SendDossierCommentsService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class SendCommentHandler
{
public function __construct(private EntityManagerInterface $em, private SendDossierCommentsService $service)
public function __construct(private CommentRepository $commentRepository, private SendDossierCommentsService $service)
{
}

/**
* @throws TransportExceptionInterface
*/
public function __invoke(SendComment $message): void
{
// do something with your message
$user = $this->em->find(User::class, $message->getUserId());
$comment = $this->em->find(Comment::class, $message->getCommentId());
$comment = $this->commentRepository->find($message->getCommentId());

// On vérifie qu'on a toutes les informations nécessaires
if($newsletter !== null && $user !== null){
if (!empty($comment) && empty($comment->getSent())) {
$this->service->send($comment);
}
}
}
}
25 changes: 20 additions & 5 deletions src/Service/SendDossierCommentsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,39 @@
namespace App\Service;

use App\Entity\Comment;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

class SendDossierCommentsService
{
public function __construct(private readonly MailerInterface $mailer)
public function __construct(private readonly MailerInterface $mailer, private EntityManagerInterface $em)
{
}

/**
* @throws TransportExceptionInterface
*/
public function send(Comment $comment): void
{
$email = (new TemplatedEmail)
->from('dossier+comment@sfdemo.fr')
->to($comment->getDossier()->getAuthor()->getEmail())
->from(new Address('dossier+comments@sfdemo.fr', 'SF-Demo'))
->to(new Address($comment->getDossier()->getAuthor()->getEmail(), $comment->getDossier()->getAuthor()->getName()))
->subject('New comment in folder: '.$comment->getDossier()->getTitle())
->htmlTemplate('emails/newsletter.html.twig')
->htmlTemplate('email/new_comment.html.twig')
->context(compact('comment'))
;

if (!empty($comment->getAuthor())) {
$email->addCc(new Address($comment->getAuthor()->getEmail(), $comment->getAuthor()->getName()));
}

$this->mailer->send($email);

$comment->setSent(new \DateTime);
$this->em->persist($comment);
$this->em->flush();
}
}
}
7 changes: 4 additions & 3 deletions templates/email/new_comment.html.twig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<h1>{{ dossier.title }}</h1>
<h3>New comments in dossier: <a href="{{ absolute_url(path('dossierItem', {'id': comment.dossier.id})) }}">{{ comment.dossier.title }}</a></h3>
<p>On {{ comment.createdDate|date('d/m/Y') }}, by {{ comment.author.username|capitalize }}.</p>

<div>
{{newsletter.content|raw}}
</div>
{{comment.content|nl2br}}
</div>

0 comments on commit d7695a4

Please sign in to comment.