Files
chill-bundles/src/Bundle/ChillMainBundle/Doctrine/Event/TrackCreateUpdateSubscriber.php

73 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Doctrine\Event;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Security;
class TrackCreateUpdateSubscriber implements EventSubscriber
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function getSubscribedEvents()
{
return [
Events::prePersist,
Events::preUpdate,
];
}
public function prePersist(LifecycleEventArgs $args): void
{
$object = $args->getObject();
if (
$object instanceof TrackCreationInterface
&& $this->security->getUser() instanceof User
) {
$object->setCreatedBy($this->security->getUser());
$object->setCreatedAt(new DateTimeImmutable('now'));
}
$this->onUpdate($object);
}
public function preUpdate(LifecycleEventArgs $args): void
{
$object = $args->getObject();
$this->onUpdate($object);
}
protected function onUpdate(object $object): void
{
if (
$object instanceof TrackUpdateInterface
&& $this->security->getUser() instanceof User
) {
$object->setUpdatedBy($this->security->getUser());
$object->setUpdatedAt(new DateTimeImmutable('now'));
}
}
}