CreationDataListener.php 1.42 KiB
<?php
/*
 * Copyright (C) 2015 IRSTEA
 * All rights reserved.
 */
namespace Irstea\FileUploadBundle\Listener;
use DateTime;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Gaufrette\Exception\FileNotFound;
use Gaufrette\Filesystem;
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.
 * @author Guillaume Perréal <guillaume.perreal@irstea.fr>
class CreationDataListener
    /**
     * @var TokenStorageInterface
    private $tokenStorage;
    /**
     * @var RequestStack
    private $requestStack;
    public function __construct(TokenStorageInterface $tokenStorage, RequestStack $requestStack)
        $this->tokenStorage = $tokenStorage;
        $this->requestStack = $requestStack;
    /**
     * @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());