nineskeletor/src/EventListener/Niveau02Subscriber.php

113 lines
3.5 KiB
PHP

<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Niveau02 as Entity;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Service\LdapService;
class Niveau02Subscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preUpdate,
Events::postUpdate,
Events::preRemove,
Events::postRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
public function postUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Impossible de supprimer si présence de registration rattaché
if(!$this->entity->getRegistrations()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des inscriptions");
// Impossible de supprimer si présence de user rattaché
if(!$this->entity->getUsers()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des utilisateurs");
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;;
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification dans annuaire
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau02"));
if(empty($ldapentrys)) {
$this->ldap->addNiveau02($this->entity);
}
elseif($this->ldap->ismodifyNiveau02($this->entity,$ldapentrys[0])) {
$this->ldap->modifyNiveau02($this->entity,$ldapentrys[0]["cn"]);
}
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau02"));
if(!empty($ldapentrys)) {
$this->ldap->deleteNiveau02($this->entity);
}
}
}
}