<?php
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class AddUserSubscriber implements EventSubscriberInterface
{
private UserPasswordHasherInterface $encode;
public function __construct(UserPasswordHasherInterface $encode)
{
$this->encode = $encode;
}
public function onKernelView(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if ($user instanceof User && $method === "POST") {
$pass = $this->encode->hashPassword($user, $user->getPassword());
$user
->setPassword($pass)
->setCreatedAt(new \DateTime('now'))
->setUpdatedAt(new \DateTime('now'))
->setRoles(['ROLE_USER'])
->setIsVerified(false);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_WRITE]
];
}
}