src/EventSubscriber/FournisseurSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Event\Produit\FournisseurCreatedEvent;
  4. use App\Repository\FournisseurRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. class FournisseurSubscriber implements EventSubscriberInterface
  8. {
  9.     /**
  10.      * @var EntityManagerInterface
  11.      */
  12.     private $entityManager;
  13.     /**
  14.      * @var FournisseurRepository
  15.      */
  16.     private $fournisseurRepository;
  17.     public function __construct(EntityManagerInterface $entityManagerFournisseurRepository $fournisseurRepository)
  18.     {
  19.         $this->entityManager $entityManager;
  20.         $this->fournisseurRepository $fournisseurRepository;
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             FournisseurCreatedEvent::class => ['onFournisseurCreated'100],
  26.         ];
  27.     }
  28.     public function onFournisseurCreated(FournisseurCreatedEvent $event)
  29.     {
  30.         $fournisseur $event->getFournisseur();
  31.         // Calcul du code comptable à attribuer
  32.         $longueur 6;
  33.         // On enlève les espaces
  34.         $nom str_replace(' '''$fournisseur->getNom().$fournisseur->getVille());
  35.         // Construction du code
  36.         $code substr($nom'0'$longueur);
  37.         // limite de boucle
  38.         $count 1;
  39.         while ($this->fournisseurRepository->codeExists($code$fournisseur) && $count 10) {
  40.             // On ajoute un chiffre à la fin
  41.             $code substr($code0$longueur-1).$count;
  42.             $count++;
  43.         }
  44.         $fournisseur->setCodeCompta(strtoupper($code));
  45.         $this->entityManager->flush();
  46.     }
  47. }