<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Behavior\IsSoftDeletable;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Events;
use Gedmo\Sortable\Sortable;

class SoftDeletableSubscriber implements EventSubscriber
{
    public function getSubscribedEvents()
    {

        return [
            Events::preRemove
        ];
    }

    public function preRemove(LifecycleEventArgs $event)
    {
        $entity = $event->getObject();
        if ($entity instanceof IsSoftDeletable) {

            if ($entity instanceof Sortable) {
                $entity->setPosition(-1);
            }
            $entity->markDeleted();
            $om = $event->getObjectManager();
            $om->persist($entity);
            $om->flush();
        }
    }
}
