Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

91 lines
2.5KB

  1. <?php
  2. namespace Lc\AdminBundle\Manager;
  3. use Doctrine\ORM\EntityManager as DoctrineEntityManager;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Lc\AdminBundle\Event\EntityManager\EntityManagerEvent;
  6. use Lc\AdminBundle\IModel\EntityInterface;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. /**
  9. * class EntityManager.
  10. *
  11. * @author Simon Vieille <simon@deblan.fr>
  12. */
  13. class EntityManager
  14. {
  15. protected EventDispatcherInterface $eventDispatcher;
  16. protected DoctrineEntityManager $entityManager;
  17. public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager)
  18. {
  19. $this->eventDispatcher = $eventDispatcher;
  20. $this->entityManager = $entityManager;
  21. }
  22. public function getRepository($className)
  23. {
  24. return $this->entityManager->getRepository($this->getEntityName($className));
  25. }
  26. public function new($className)
  27. {
  28. return new $this->getEntityName($className);
  29. }
  30. public function create(EntityInterface $entity): self
  31. {
  32. $this->persist($entity);
  33. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
  34. return $this;
  35. }
  36. public function update(EntityInterface $entity): self
  37. {
  38. $this->persist($entity);
  39. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::UPDATE_EVENT);
  40. return $this;
  41. }
  42. public function delete(EntityInterface $entity): self
  43. {
  44. $this->remove($entity);
  45. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::DELETE_EVENT);
  46. return $this;
  47. }
  48. public function flush(): self
  49. {
  50. $this->entityManager->flush();
  51. return $this;
  52. }
  53. public function clear(): self
  54. {
  55. $this->entityManager->clear();
  56. return $this;
  57. }
  58. protected function persist(EntityInterface $entity)
  59. {
  60. $this->entityManager->persist($entity);
  61. }
  62. public function getEntityName($className)
  63. {
  64. if (substr($className, -9) === 'Interface') {
  65. return $this->entityManager->getClassMetadata($className)->getName();
  66. }else{
  67. return $className;
  68. }
  69. }
  70. }