예제 #1
0
파일: Creator.php 프로젝트: t4web/domain
 public function handle($criteria, $data)
 {
     $entity = $this->entityFactory->create($data);
     if ($this->eventManager) {
         $event = $this->eventManager->createEvent('create.pre', $entity, $data);
         $this->eventManager->trigger($event);
     }
     $this->repository->add($entity);
     if ($this->eventManager) {
         $event = $this->eventManager->createEvent('create.post', $entity, $data);
         $this->eventManager->trigger($event);
     }
     return $entity;
 }
 /**
  * @param CriteriaInterface|array $criteria
  * @return EntityInterface|null
  */
 public function find($criteria)
 {
     if (is_array($criteria)) {
         $criteria = $this->createCriteria($criteria);
     }
     if (empty($this->with)) {
         return $this->entityRepository->find($criteria);
     }
     /** @var Select $select */
     $select = $criteria->getQuery();
     $select->limit(1)->offset(0);
     $result = $this->tableGateway->selectWith($select)->toArray();
     if (!isset($result[0])) {
         return;
     }
     $row = $result[0];
     $relatedEntityIds = [];
     foreach ($this->with as $relatedEntityName => $cascadeWith) {
         $relatedField = $this->getRelatedField($relatedEntityName);
         if (!array_key_exists($relatedField, $row)) {
             throw new \RuntimeException(get_class($this) . ": relation field {$relatedEntityName} not fetched");
         }
         if (!isset($relatedEntityIds[$relatedEntityName])) {
             $relatedEntityIds[$relatedEntityName] = new ArrayObject();
         }
         if (!in_array($row[$relatedField], (array) $relatedEntityIds[$relatedEntityName])) {
             $relatedEntityIds[$relatedEntityName]->append($row[$relatedField]);
         }
     }
     $relatedEntities = [];
     foreach ($this->with as $relatedEntityName => $cascadeWith) {
         if (empty((array) $relatedEntityIds[$relatedEntityName])) {
             continue;
         }
         $criteria = $this->relatedRepository[$relatedEntityName]->createCriteria(['id.in' => (array) $relatedEntityIds[$relatedEntityName]]);
         $relatedEntities[$relatedEntityName] = $this->relatedRepository[$relatedEntityName]->findMany($criteria);
     }
     $relatedField = $this->getRelatedField($relatedEntityName);
     $entityArgs = ['data' => $this->mapper->fromTableRow($row)];
     foreach ($this->relationsConfig as $entityName => $joinRule) {
         if (isset($relatedEntities[$entityName])) {
             if (isset($relatedEntities[$entityName][$row[$relatedField]])) {
                 $entityArgs['aggregateItems'][] = $relatedEntities[$entityName][$row[$relatedField]];
             } else {
                 $entityArgs['aggregateItems'][] = null;
             }
         } else {
             $entityArgs['aggregateItems'][] = null;
         }
     }
     $entity = $this->entityFactory->create($entityArgs);
     $this->with = null;
     return $entity;
 }