<?php
// api/src/EventSubscriber/DemandeIdGeneratorSubscriber.php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Demande;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class DemandeNumberGeneratorSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['generateId', EventPriorities::PRE_WRITE],
];
}
public function generateId(ViewEvent $event)
{
$demande = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$demande instanceof Demande || (Request::METHOD_POST !== $method && Request::METHOD_PATCH !== $method && Request::METHOD_PUT !== $method)) {
return;
}
if ($demande->getStatus() == Demande::DRAFT) {
return;
}
if ($demande->getNumber() && strlen($demande->getNumber()) > 0) {
return;
}
// Si la demande est la suite d'une demande alors on va plutôt généré le numéro à partir de l'ancien
if ($demande->getPreviousDemande()) {
$number = $this->getNewDemandeNumber($demande);
$demande->setNumber($number);
}
//on set les variable connues :
// {Y} => date('Y')
$vars = [
'{Y}' => date('Y'),
'{BU}' => $demande->getBusinessUnit()->getCode(),
];
$number = $demande->getForm()->getAbreviation();
foreach ($vars as $var => $value) {
$number = str_replace($var, $value, $number);
}
// on trouve la valeur de l'auto-incrément
$genericNumber = str_replace('{AI}', '%', $number);
$nbOfValues = $this->em->getRepository(Demande::class)->countByGenericNumber($genericNumber);
$nbOfValues++;
$number = str_replace('{AI}', str_pad($nbOfValues, 3, '0', STR_PAD_LEFT), $number);
$demande->setNumber($number);
}
public function getNewDemandeNumber(Demande $demande)
{
// On récupère les ancien Token
$tokens = [];
preg_match('/({.*})/', $demande->getPreviousDemande()->getForm()->getAbreviation(), $tokens);
// on génère la regexp qui permet de récupérer les ancien match
$replacments = [];
foreach ($tokens as $token) {
}
// Pour chaque token on récupère la valeur
// On génère le numéro de la nouvelle demande
preg_match('##', $demande->getNumber(), $matches);
return '';
}
}