<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Block;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Lexik\Bundle\JWTAuthenticationBundle\Security\User\JWTUser;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
// use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Security;
final class AddOwnerEntityToItemSubscriber implements EventSubscriberInterface
{
private $security;
private $doctrine;
public function __construct(Security $security, ManagerRegistry $doctrine)
{
$this->security = $security;
$this->doctrine = $doctrine;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['attachOwner', EventPriorities::PRE_WRITE],
];
}
public function attachOwner(ViewEvent $event)
{
$item = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (Request::METHOD_POST !== $method && Request::METHOD_PUT !== $method) {
// On ne gère que la création et la modification
// die('PAS LA BONE METHODE');
return;
}
if ( ! method_exists ( $item , 'getOwner' ) || !method_exists ( $item , 'getEntity' ) )
{
// throw new \Exception('PAS DE METHODE getowner');
return;
}
// maybe these extra null checks are not even needed
$owner = $this->security->getUser();
/*
$token = $this->tokenStorage->getToken();
if (!$token) {
// throw new \Exception('PAS DE TOKEN');
return;
}
$owner = $token->getUser();
*/
if (!$owner instanceof JWTUser) {
// throw new \Exception('PAS UN JWTUSER');
return;
}
$username = $owner->getUsername();
$owner = $this->doctrine->getRepository('App\\Entity\\User')->findOneBy(['username' => $username]);
$entity = $owner->getEntity();
// En création on renseigne le owner et son entité
if (Request::METHOD_POST === $method) {
// throw new \Exception('YES ON MAJ');
// On ne gère que la création et la modification
// Attach the user to the not yet persisted Article
$item->setOwner($owner);
// l'entité du user
$item->setEntity($entity);
// la date de création
if (method_exists ( $item , 'setCreatedAt' ) )
$item->setCreatedAt(new \DateTime());
} else {
// throw new \Exception('PAS UN POST UN MAJ');
$item->setOwner($owner);
}
// Dans tous les cas on renseigne la date de modification
if (method_exists ( $item , 'setUpdatedAt' ) )
$item->setUpdatedAt(new \DateTime());
}
}