Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

105 lines
3.1KB

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