tinternet.net/src/Manager/EntityManager.php

99 lines
2.6 KiB
PHP
Raw Normal View History

2021-03-16 10:37:12 +01:00
<?php
namespace App\Manager;
2021-03-17 12:44:02 +01:00
use App\Entity\EntityInterface;
2021-03-16 10:37:12 +01:00
use App\Event\EntityManager\EntityManagerEvent;
use Doctrine\ORM\EntityManager as DoctrineEntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* class EntityManager.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class EntityManager
{
protected EventDispatcherInterface $eventDispatcher;
protected DoctrineEntityManager $entityManager;
public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager)
{
$this->eventDispatcher = $eventDispatcher;
$this->entityManager = $entityManager;
}
public function create(EntityInterface $entity, bool $dispatchEvent = true): self
2021-03-16 10:37:12 +01:00
{
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::PRE_CREATE_EVENT);
}
2021-03-17 20:42:09 +01:00
2021-03-16 10:37:12 +01:00
$this->persist($entity);
2021-03-17 20:42:09 +01:00
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
}
2021-03-16 10:37:12 +01:00
return $this;
}
public function update(EntityInterface $entity, bool $dispatchEvent = true): self
2021-03-16 10:37:12 +01:00
{
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::PRE_UPDATE_EVENT);
}
2021-03-17 20:42:09 +01:00
2021-03-16 10:37:12 +01:00
$this->persist($entity);
2021-03-17 20:42:09 +01:00
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::UPDATE_EVENT);
}
2021-03-16 10:37:12 +01:00
return $this;
}
public function delete(EntityInterface $entity, bool $dispatchEvent = true): self
2021-03-16 10:37:12 +01:00
{
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::PRE_DELETE_EVENT);
}
2021-03-17 20:42:09 +01:00
2021-03-17 12:44:02 +01:00
$this->entityManager->remove($entity);
2021-03-17 15:57:07 +01:00
$this->flush();
if ($dispatchEvent) {
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::DELETE_EVENT);
}
2021-03-16 10:37:12 +01:00
return $this;
}
public function flush(): self
{
$this->entityManager->flush();
return $this;
}
public function clear(): self
{
$this->entityManager->clear();
return $this;
}
public function getEntityManager(): EntityManagerInterface
{
return $this->entityManager;
}
2021-03-17 12:44:02 +01:00
protected function persist(EntityInterface $entity)
2021-03-16 10:37:12 +01:00
{
$this->entityManager->persist($entity);
2021-03-17 15:57:07 +01:00
$this->flush();
2021-03-16 10:37:12 +01:00
}
}