<?php
namespace App\EventSubscriber;
use App\Entity\InstallsReleases;
use App\Entity\User;
use DateTime;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Security;
class EasyAdminSubscriber implements EventSubscriberInterface
{
private $security;
private $encoder;
public function __construct(Security $security,UserPasswordHasherInterface $encoder)
{
$this->security = $security;
$this->encoder = $encoder;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => (['setBeforeCreate']),
AfterEntityUpdatedEvent::class => ['setUpdatedAt'],
];
}
public function setUpdatedAt(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
$entity->setUpdatedAt(new DateTime());
}
public function setBeforeCreate(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof InstallsReleases) {
$versionFull = $entity->getVersionFull();
$versionNumbers = explode('.', $versionFull);
if (count($versionNumbers) > 1) {
$entity->setVersionShort($versionNumbers[0] . '.' . $versionNumbers[1]);
} else {
$entity->setVersionShort($versionFull);
}
}
$user = $this->security->getUser();
if (!$entity instanceof User) {
$entity->setCreatedBy($user);
}else{
$password = $this->encoder->hashPassword($entity, $entity->getPassword());
$entity->setPassword($password);
}
}
}