|
- <?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;
- }
-
- }
- }
|