FluxListener.php 1.32 KB
Newer Older
Damien Moulard committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<?php
namespace App\Listener;

use App\Entity\Flux;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\Security\Core\Security;

class FluxListener implements EventSubscriber
{
    private $em;
    private $security;

    public function __construct(EntityManagerInterface $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    public function getSubscribedEvents()
    {
        return array(Events::onFlush);
    }

    public function onFlush(OnFlushEventArgs $args)
    {
        $em  = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        $inserted = $uow->getScheduledEntityInsertions();

        foreach ($inserted as $entity) {
            if ($entity instanceof Flux) {
                $topersists = $entity->operate($em);
                foreach ($topersists as $topersist) {
                    $class = $em->getClassMetadata(get_class($topersist));
                    $em->persist($topersist);
                    $em->getUnitOfWork()->computeChangeSet($class, $topersist);
                }
                // @TODO : do something (log, save somewhere else...) on flux persist
                //      => @tag sur un service ?
            }
        }
    }
}