/** * Adds an entity to the repo * * @param object $entity The entity to add * * @return void * * @throws OrmException if the entity could not be added */ public function add($entity) { $idAccessorRegistry = $this->unitOfWork->getEntityRegistry()->getIdAccessorRegistry(); $entityId = $idAccessorRegistry->getEntityId($entity); $mapClass = $this->mapRepository->getEntityClass(); if (empty($entityId)) { $this->entityRepository->add($entity); $map = new $mapClass(); $varJoinName = $this->relation->varJoinName(); $this->mapRepository->add($map); $this->unitOfWork->getEntityRegistry()->registerAggregateRootCallback($entity, $map, function ($root, $child) use($varJoinName, $idAccessorRegistry) { $entityId = $idAccessorRegistry->getEntityId($root); $child->{$varJoinName} = $entityId; $this->map[] = $entityId; }); return; } if (in_array($entityId, $this->map)) { throw new OrmException("Entity with id {$entityId} aleady exists"); } $map = new $mapClass(); $varJoinName = $this->relation->varJoinName(); $map->{$varJoinName} = $entityId; $this->mapRepository->add($map); $this->map[] = $entityId; }
/** * Constructor * * @param RepositoryInterface $entityRepository The entity repository * @param RepositoryInterface $mapRepository The mapping repository * @param HasManyThrough $relation The relation * @param UnitOfWorkInterface $unitOfWork The unit of work */ public function __construct(RepoInterface $entityRepository, RepoInterface $mapRepository, HasManyThrough $relation, UnitOfWorkInterface $unitOfWork) { $this->entityRepository = $entityRepository; $this->mapRepository = $mapRepository; $this->relation = $relation; $this->className = $entityRepository->getEntityClass(); $this->unitOfWork = $unitOfWork; }