<?php
namespace App\EventSubscriber;
use App\Event\Produit\FournisseurCreatedEvent;
use App\Repository\FournisseurRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FournisseurSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var FournisseurRepository
*/
private $fournisseurRepository;
public function __construct(EntityManagerInterface $entityManager, FournisseurRepository $fournisseurRepository)
{
$this->entityManager = $entityManager;
$this->fournisseurRepository = $fournisseurRepository;
}
public static function getSubscribedEvents(): array
{
return [
FournisseurCreatedEvent::class => ['onFournisseurCreated', 100],
];
}
public function onFournisseurCreated(FournisseurCreatedEvent $event)
{
$fournisseur = $event->getFournisseur();
// Calcul du code comptable à attribuer
$longueur = 6;
// On enlève les espaces
$nom = str_replace(' ', '', $fournisseur->getNom().$fournisseur->getVille());
// Construction du code
$code = substr($nom, '0', $longueur);
// limite de boucle
$count = 1;
while ($this->fournisseurRepository->codeExists($code, $fournisseur) && $count < 10) {
// On ajoute un chiffre à la fin
$code = substr($code, 0, $longueur-1).$count;
$count++;
}
$fournisseur->setCodeCompta(strtoupper($code));
$this->entityManager->flush();
}
}