CreationDataListener.php 1.37 KiB
<?php declare(strict_types=1);
/*
 * Copyright (C) 2015-2017 IRSTEA
 * All rights reserved.
 */
namespace Irstea\FileUploadBundle\Listener;
use DateTime;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Irstea\FileUploadBundle\Model\UploadedFileInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
 * Ajoute les informations sur la date, l'utilisateur connecté et l'adresse IP du client dans le fichier.
class CreationDataListener
    /**
     * @var TokenStorageInterface
    private $tokenStorage;
    /**
     * @var RequestStack
    private $requestStack;
    public function __construct(TokenStorageInterface $tokenStorage, RequestStack $requestStack)
        $this->tokenStorage = $tokenStorage;
        $this->requestStack = $requestStack;
    /**
     * @param UploadedFileInterface $file
     * @param LifecycleEventArgs    $event
    public function prePersist(UploadedFileInterface $file, LifecycleEventArgs $event)
        $file->setCreatedAt(new DateTime('now'));
        if ($request = $this->requestStack->getCurrentRequest()) {
            $file->setCreatedFrom($request->getClientIp());
        if ($token = $this->tokenStorage->getToken()) {
            $file->setCreatedBy($token->getUsername());