|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
-
- namespace Lc\ShopBundle\Manager;
-
- use Doctrine\ORM\EntityManagerInterface;
- use Lc\ShopBundle\Context\UserInterface;
- use Lc\ShopBundle\Event\EntityManager\EntityManagerEvent;
- use Symfony\Component\EventDispatcher\EventDispatcherInterface;
- use Symfony\Component\Security\Core\Security;
-
- /**
- * class EntityManager.
- *
- * @author Simon Vieille <simon@deblan.fr>
- */
- class EntityManager
- {
- protected $eventDispatcher;
- protected $entityManager;
- protected $security;
- protected $userSystem = null;
-
- public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager, Security $security)
- {
- $this->eventDispatcher = $eventDispatcher;
- $this->entityManager = $entityManager;
- $this->security = $security;
- }
-
-
- public function getUserSystem()
- {
- if ($this->userSystem === null) {
- $this->userSystem = $this->getRepository(UserInterface::class)->findOneByDevAlias('system');
- }
- return $this->userSystem;
- }
-
- public function getRepository($className)
- {
- return $this->entityManager->getRepository($this->getEntityName($className));
- }
-
-
- public function create($entity): self
- {
-
- if ($this->security->getUser() === null) {
- $entity->setUpdatedBy($this->getUserSystem());
- $entity->setCreadtedBy($this->getUserSystem());
- }
- $this->persist($entity);
- $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
- return $this;
- }
-
- public function update($entity): self
- {
- if ($this->security->getUser() === null) {
- $entity->setUpdatedBy($this->getUserSystem());
- }
- $this->persist($entity);
- $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::UPDATE_EVENT);
-
- return $this;
- }
-
- public function delete($entity): self
- {
- $this->remove($entity);
- $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::DELETE_EVENT);
-
- return $this;
- }
-
- public function flush(): self
- {
- $this->entityManager->flush();
-
- return $this;
- }
-
- public function clear(): self
- {
- $this->entityManager->clear();
-
- return $this;
- }
-
- protected function persist($entity)
- {
- $this->entityManager->persist($entity);
- }
-
- public function getEntityName($className)
- {
- if (substr($className, -9) === 'Interface') {
- return $this->entityManager->getClassMetadata($className)->getName();
- } else {
- return $className;
- }
-
- }
- }
|