src/EventSubscriber/LearningAgreementWriteSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\LearningAgreement;
  5. use App\LearningAgreement\Enum\LearningAgreementStatus;
  6. use App\Pdf\Pdf;
  7. use JetBrains\PhpStorm\ArrayShape;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. class LearningAgreementWriteSubscriber implements EventSubscriberInterface
  13. {
  14.     private Pdf $pdf;
  15.     public function __construct(
  16.         Pdf $pdf,
  17.     ) {
  18.         $this->pdf $pdf;
  19.     }
  20.     #[ArrayShape([KernelEvents::VIEW => 'array'])]
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::VIEW => [
  25.                 'generateLaPdf'EventPriorities::PRE_WRITE,
  26.             ],
  27.         ];
  28.     }
  29.     public function generateLaPdf(ViewEvent $viewEvent): void
  30.     {
  31.         $entity $viewEvent->getControllerResult();
  32.         $method $viewEvent->getRequest()->getMethod();
  33.         if (
  34.             !$entity instanceof LearningAgreement
  35.             || !in_array(
  36.                 $method,
  37.                 [
  38.                     Request::METHOD_POST,
  39.                     Request::METHOD_PATCH,
  40.                     Request::METHOD_PUT,
  41.                 ]
  42.             )
  43.         ) {
  44.             return;
  45.         }
  46.         // Only regenerate PDF if the learning agreement's status is ACCEPTED_BY_RECEIVING
  47.         if (LearningAgreementStatus::ACCEPTED_BY_RECEIVING === $entity->getStatus()) {
  48.             $pdfName 'Learning agreement - '.$entity->getMobility()->getId().'.pdf';
  49.             $pdfPathSubDirectory 'learning_agreement';
  50.             // Generate PDF according to LA's data
  51.             $relativePathWithName $this->pdf->generateFromHtml(
  52.                 $pdfName,
  53.                 $pdfPathSubDirectory,
  54.                 'pdf/learning_agreement_pdf.html.twig',
  55.                 [
  56.                     'learningAgreement' => $entity,
  57.                 ]
  58.             );
  59.             // Save PDF url to LA if changed
  60.             $entity->setPdf($relativePathWithName);
  61.         }
  62.     }
  63. }