src/Controller/EmailController.php line 81

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use App\Exception\ApiException\ApiDeserializeException;
  5. use App\Exception\ApiException\ApiEmailSendException;
  6. use App\Exception\ApiException\ApiValidationException;
  7. use App\Exception\ApiException\NotFoundException;
  8. use App\Model\Email;
  9. use App\Model\EmailMessage;
  10. use App\Model\EmailSearchMessage;
  11. use App\Service\EmailService;
  12. use Nelmio\ApiDocBundle\Annotation\Model;
  13. use Nelmio\ApiDocBundle\Annotation\Security;
  14. use OpenApi\Annotations as OA;
  15. use Psr\Log\LoggerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  21. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  22. use Symfony\Component\Mime\Address;
  23. use Symfony\Component\Mime\Part\DataPart;
  24. use Symfony\Component\Routing\Annotation\Route;
  25. use Symfony\Component\Serializer\SerializerInterface;
  26. class EmailController extends AbstractController
  27. {
  28.     /** @var LoggerInterface */
  29.     protected $log;
  30.     /** @var SerializerInterface */
  31.     private $serializer;
  32.     /** @var EmailService */
  33.     private $emailService;
  34.     public function __construct(
  35.         LoggerInterface $log,
  36.         SerializerInterface $serializer,
  37.         EmailService $emailService
  38.     ) {
  39.         $this->log $log;
  40.         $this->serializer $serializer;
  41.         $this->emailService $emailService;
  42.     }
  43.     /**
  44.      * Send an email
  45.      *
  46.      * @OA\Tag(name="email")
  47.      * @OA\Post(summary="Send a mail with a template")
  48.      *
  49.      * @OA\RequestBody(
  50.      *         description="Input data format",
  51.      *         @OA\JsonContent(ref=@Model(type=Email::class)),
  52.      * )
  53.      * @OA\Response(
  54.      *     response=200,
  55.      *     description="Email sent"
  56.      * ),
  57.      * @OA\Response(
  58.      *     response=400,
  59.      *     description="If the request is incorrect, an array of errors will be returned."
  60.      * )
  61.      * @OA\Response(
  62.      *     response=403,
  63.      *     description="Access token does not have the required scope"
  64.      * ),
  65.      * @Security(name="Bearer")
  66.      *
  67.      * @param Request $request
  68.      *
  69.      * @return JsonResponse
  70.      * @throws ApiDeserializeException
  71.      * @throws ApiEmailSendException
  72.      * @throws ApiValidationException
  73.      */
  74.     #[Route(path'/email/send'name'post_email_send'methods: ['POST'])]
  75.     public function send(Request $request)
  76.     {
  77.         try {
  78.             /** @var Email $email */
  79.             $email $this->serializer->deserialize($request->getContent(), Email::class, 'json');
  80.         } catch (\Exception $e) {
  81.             throw new ApiDeserializeException($e->getMessage());
  82.         }
  83.         $templatedEmail $this->emailService->generateTemplatedEmail($email);
  84.         if (true === $email->isDebug()) {
  85.             return new JsonResponse([
  86.                 'subject' => $templatedEmail->getSubject(),
  87.                 'from' => array_map(fn (Address $address) => $address->toString(), $templatedEmail->getFrom()),
  88.                 'to' => array_map(fn (Address $address) => $address->toString(), $templatedEmail->getTo()),
  89.                 'cc' => array_map(fn (Address $address) => $address->toString(), $templatedEmail->getCc()),
  90.                 'bcc' => array_map(fn (Address $address) => $address->toString(), $templatedEmail->getBcc()),
  91.                 'locale' => $email->getLocale(),
  92.                 'attachments' => array_map(fn (DataPart $attachment) => $attachment->asDebugString(), $templatedEmail->getAttachments()),
  93.                 'template' => $email->getTemplatePath(),
  94.                 'templateData' => $email->getTemplateData(),
  95.                 'htmlBody' => $templatedEmail->getHtmlBody(),
  96.             ], Response::HTTP_OK);
  97.         }
  98.         $this->emailService->send($templatedEmail);
  99.         return new JsonResponse([
  100.             'success' => true,
  101.         ], Response::HTTP_OK);
  102.     }
  103.     /**
  104.      * Search emails by query
  105.      *
  106.      * @OA\Tag(name="email")
  107.      * @OA\Get(
  108.      *     summary="Search emails by query",
  109.      *     description="Search emails by query syntax by SendGrid Filter all messages API (https://docs.sendgrid.com/api-reference/e-mail-activity/filter-all-messages)",
  110.      *     @OA\Parameter(
  111.      *         name="query",
  112.      *         in="query",
  113.      *         description="SendGrid request to filter returned emails (see=https://docs.sendgrid.com/for-developers/sending-email/getting-started-email-activity-api#query-reference)",
  114.      *         required=true,
  115.      *         example="subject LIKE '%marchand%'",
  116.      *         @OA\Schema(
  117.      *             type="string"
  118.      *         ),
  119.      *     ),
  120.      *     @OA\Parameter(
  121.      *         name="limit",
  122.      *         in="query",
  123.      *         description="Limit the number of information returned",
  124.      *         @OA\Schema(
  125.      *             type="integer"
  126.      *         ),
  127.      *     ),
  128.      * )
  129.      * @OA\Response(
  130.      *     response=200,
  131.      *     description="List of email messages to JSON",
  132.      *     @OA\JsonContent(
  133.      *      type="array",
  134.      *      @OA\Items(ref=@Model(type=EmailSearchMessage::class))),
  135.      * )
  136.      * @OA\Response(
  137.      *     response=400,
  138.      *     description="If the request is incorrect, an array of errors will be returned."
  139.      * )
  140.      * @OA\Response(
  141.      *     response=403,
  142.      *     description="Access token does not have the required scope"
  143.      * )
  144.      * @Security(name="Bearer")
  145.      *
  146.      * @param Request $request
  147.      *
  148.      * @return JsonResponse
  149.      * @throws BadRequestHttpException
  150.      */
  151.     #[Route(path'/email/search'methods: ['GET'], name'get_email_search')]
  152.     public function search(Request $request)
  153.     {
  154.         $query $request->get('query''');
  155.         $limit $request->get('limit''');
  156.         if (preg_match('/\d+/'$limit)) {
  157.             $limit = (int) $limit;
  158.         } else {
  159.             $limit 0;
  160.         }
  161.         try {
  162.             return new JsonResponse(
  163.                 $this->emailService->findMessagesByQuery($query$limit),
  164.                 Response::HTTP_OK
  165.             );
  166.         } catch (\Throwable $t) {
  167.             throw new BadRequestHttpException(sprintf('Error on search messages by query: %s'$t->getMessage()), $t);
  168.         }
  169.     }
  170.     /**
  171.      * Search email by ID
  172.      *
  173.      * @OA\Tag(name="email")
  174.      * @OA\Get(
  175.      *     summary="Search email by ID",
  176.      *     description="Search email by ID by SendGrid Filter messages by message ID (https://docs.sendgrid.com/api-reference/e-mail-activity/filter-all-messages)",
  177.      *     @OA\Parameter(
  178.      *         name="messageId",
  179.      *         in="path",
  180.      *         description="The ID of the message you are requesting details for.",
  181.      *         required=true,
  182.      *         example="ZuL4ObErRj2LcetrX95S5A.filterdrecv-59cb65cf6d-7z4fb-1-6436AA0F-27.0",
  183.      *         @OA\Schema(
  184.      *             type="string"
  185.      *         ),
  186.      *     ),
  187.      * )
  188.      * @OA\Response(
  189.      *     response=200,
  190.      *     description="Email message result to JSON",
  191.      *     @OA\JsonContent(ref=@Model(type=EmailMessage::class)),
  192.      * ),
  193.      * @OA\Response(
  194.      *     response=400,
  195.      *     description="If the request is incorrect, an array of errors will be returned."
  196.      * ),
  197.      * @OA\Response(
  198.      *     response=404,
  199.      *     description="If no message found with id."
  200.      * ),
  201.      * @OA\Response(
  202.      *     response=403,
  203.      *     description="Access token does not have the required scope"
  204.      * ),
  205.      * @Security(name="Bearer")
  206.      *
  207.      * @param string $messageId
  208.      *
  209.      * @return JsonResponse
  210.      * @throws NotFoundHttpException
  211.      * @throws BadRequestHttpException
  212.      */
  213.     #[Route(path'/email/search/{messageId}'methods: ['GET'], name'get_email_search_by_id')]
  214.     public function searchById(string $messageId)
  215.     {
  216.         try {
  217.             return new JsonResponse(
  218.                 $this->emailService->findMessageById($messageId),
  219.                 Response::HTTP_OK
  220.             );
  221.         } catch (NotFoundException $t) {
  222.             throw new NotFoundHttpException($t->getMessage());
  223.         } catch (\Throwable $t) {
  224.             throw new BadRequestHttpException(sprintf('Error on search messages by id "%s": %s'$messageId$t->getMessage()), $t);
  225.         }
  226.     }
  227. }