src/EventSubscriber/EasyAdminSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\InstallsReleases;
  4. use App\Entity\User;
  5. use DateTime;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. class EasyAdminSubscriber implements EventSubscriberInterface
  12. {
  13.     private $security;
  14.     private $encoder;
  15.     public function __construct(Security $security,UserPasswordHasherInterface $encoder)
  16.     {
  17.         $this->security $security;
  18.         $this->encoder $encoder;
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return [
  23.             BeforeEntityPersistedEvent::class => (['setBeforeCreate']),
  24.             AfterEntityUpdatedEvent::class => ['setUpdatedAt'],
  25.         ];
  26.     }
  27.     public function setUpdatedAt(AfterEntityUpdatedEvent $event)
  28.     {
  29.         $entity $event->getEntityInstance();
  30.         $entity->setUpdatedAt(new DateTime());
  31.     }
  32.     public function setBeforeCreate(BeforeEntityPersistedEvent $event)
  33.     {
  34.         $entity $event->getEntityInstance();
  35.         if ($entity instanceof InstallsReleases) {
  36.             $versionFull $entity->getVersionFull();
  37.             $versionNumbers explode('.'$versionFull);
  38.             if (count($versionNumbers) > 1) {
  39.                 $entity->setVersionShort($versionNumbers[0] . '.' $versionNumbers[1]);
  40.             } else {
  41.                 $entity->setVersionShort($versionFull);
  42.             }
  43.         }
  44.         $user $this->security->getUser();
  45.         if (!$entity instanceof User) {
  46.             $entity->setCreatedBy($user);
  47.         }else{
  48.             $password $this->encoder->hashPassword($entity$entity->getPassword());
  49.             $entity->setPassword($password);
  50.         }
  51.     }
  52. }