getDocumentCollection() public method

Returns the MongoCollection instance for a class.
public getDocumentCollection ( string $className ) : Doctrine\MongoDB\Collection
$className string The class name.
return Doctrine\MongoDB\Collection
 protected function tearDown()
 {
     $documentClasses = array('Saxulum\\Tests\\DoctrineMongodbOdmManagerRegistry\\Document\\Document', 'Saxulum\\Tests\\DoctrineMongodbOdmManagerRegistry\\Document\\Category');
     foreach ($documentClasses as $class) {
         $this->dm->getDocumentCollection($class)->drop();
     }
     parent::tearDown();
 }
 protected function tearDown()
 {
     $documentClasses = array('Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Document', 'Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Category', 'Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Guesser');
     foreach ($documentClasses as $class) {
         $this->dm->getDocumentCollection($class)->drop();
     }
     parent::tearDown();
 }
 protected function tearDown()
 {
     $documentClasses = [Document::class, Category::class];
     foreach ($documentClasses as $class) {
         $this->dm->getDocumentCollection($class)->drop();
     }
     parent::tearDown();
 }
 /**
  * {@inheritDoc}
  */
 protected function batchInsertPendingVersions(array $pendingVersions)
 {
     $mongodbVersions = [];
     foreach ($pendingVersions as $pendingVersion) {
         $mongodbVersions[] = $this->normalizer->normalize($pendingVersion, VersionNormalizer::FORMAT);
     }
     $collection = $this->documentManager->getDocumentCollection($this->versionClass);
     $collection->batchInsert($mongodbVersions);
 }
示例#5
0
 /**
  *
  * @param \Ricklab\Location\Point $point
  * @param int $limit Limit the results to a number
  * @param int $offset Start from this item
  * @return \Doctrine\MongoDB\ArrayIterator
  */
 public function getLocationsAround(Loc\Point $point, $limit, $offset = 0)
 {
     $locations = $this->doctrine->getDocumentCollection('CraftLocationBundle:Location')->aggregate(['$geoNear' => ['near' => $point->jsonSerialize(), 'limit' => (int) $limit, 'skip' => $offset, 'spherical' => true, 'distanceField' => 'distance']]);
     /*  $locations = $this->getMongoLocationCollection()
         ->createQueryBuilder()
         ->geoNear($x, $y)
         ->limit((int) $limit)
         ->skip($offset)->getQuery(); */
     return $locations;
 }
 /**
  * {@inheritdoc}
  */
 public function saveAll(array $versions, array $options = [])
 {
     $normalizedVersions = [];
     foreach ($versions as $version) {
         $normalizedVersions[] = $this->normalizer->normalize($version, VersionNormalizer::FORMAT);
     }
     if (0 < count($normalizedVersions)) {
         $collection = $this->documentManager->getDocumentCollection($this->versionClass);
         $collection->batchInsert($normalizedVersions);
     }
 }
 function let(DocumentManager $documentManager, PendingMassPersister $pendingPersister, NormalizerInterface $normalizer, EventDispatcherInterface $eventDispatcher, MongoObjectsFactory $mongoFactory, StepExecution $stepExecution, Collection $collection, CacheClearer $clearer)
 {
     $documentManager->getDocumentCollection('pim_product')->willReturn($collection);
     $collection->getName()->willReturn('pim_product_collection');
     $this->beConstructedWith($documentManager, $pendingPersister, $normalizer, $eventDispatcher, $mongoFactory, 'pim_product', $clearer);
     $this->setStepExecution($stepExecution);
 }
 /**
  * Save the completenesses data for the product directly to MongoDB.
  *
  * @param string $productId
  * @param array  $compData
  */
 protected function saveCompletenesses($productId, array $compData)
 {
     $completenesses = $compData['completenesses'];
     $all = $compData['all'];
     $collection = $this->documentManager->getDocumentCollection($this->productClass);
     $query = ['_id' => $productId];
     $options = ['multiple' => false];
     if ($all) {
         $compObjects = [];
         $normalizedComps = [];
         foreach ($completenesses as $key => $value) {
             $compObject = $value['object'];
             $compObject['_id'] = new \MongoId();
             $compObjects[] = $compObject;
             $normalizedComps[$key] = $value['ratio'];
         }
         $normalizedComps = ['normalizedData.completenesses' => $normalizedComps];
         $compObject = ['$set' => ['completenesses' => $compObjects]];
         $collection->update($query, $compObject, $options);
         $normalizedComp = ['$set' => $normalizedComps];
         $collection->update($query, $normalizedComp, $options);
     } else {
         foreach ($completenesses as $key => $value) {
             $compObject = ['$push' => ['completenesses' => $value['object']]];
             $collection->update($query, $compObject, $options);
             $normalizedComp = ['$set' => ['normalizedData.completenesses.' . $key => $value['ratio']]];
             $collection->update($query, $normalizedComp, $options);
         }
     }
 }
    public function loadCollection(PersistentCollection $collection)
    {
        $mapping = $collection->getMapping();
        $cmd = $this->dm->getConfiguration()->getMongoCmd();
        $groupedIds = array();
        foreach ($collection->getReferences() as $reference) {
            $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference);
            $id = $reference[$cmd . 'id'];
            $reference = $this->dm->getReference($className, (string) $id);
            $collection->add($reference);
            if ($reference instanceof Proxy && ! $reference->__isInitialized__) {
                if ( ! isset($groupedIds[$className])) {
                    $groupedIds[$className] = array();
                }
                $groupedIds[$className][] = $id;
            }
        }

        foreach ($groupedIds as $className => $ids) {
            $mongoCollection = $this->dm->getDocumentCollection($className);
            $data = $mongoCollection->find(array('_id' => array($cmd . 'in' => $ids)));
            $hints = array(Builder::HINT_REFRESH => true);
            foreach ($data as $id => $documentData) {
                $document = $this->uow->getOrCreateDocument($className, $documentData, $hints);
            }
        }
    }
示例#10
0
 /**
  * Ensure sharding for collection by document name.
  *
  * @param string $documentName
  * @param array  $indexOptions Options for `ensureIndex` command. It's performed on an existing collections.
  *
  * @throws MongoDBException
  */
 public function ensureDocumentSharding($documentName, array $indexOptions = array())
 {
     $class = $this->dm->getClassMetadata($documentName);
     if (!$class->isSharded()) {
         return;
     }
     $this->enableShardingForDbByDocumentName($documentName);
     $try = 0;
     do {
         $result = $this->runShardCollectionCommand($documentName);
         $done = true;
         // Need to check error message because MongoDB 3.0 does not return a code for this error
         if ($result['ok'] != 1 && strpos($result['errmsg'], 'please create an index that starts') !== false) {
             // The proposed key is not returned when using mongo-php-adapter with ext-mongodb.
             // See https://github.com/mongodb/mongo-php-driver/issues/296 for details
             if (isset($result['proposedKey'])) {
                 $key = $result['proposedKey'];
             } else {
                 $key = $this->dm->getClassMetadata($documentName)->getShardKey()['keys'];
             }
             $this->dm->getDocumentCollection($documentName)->ensureIndex($key, $indexOptions);
             $done = false;
             $try++;
         }
     } while (!$done && $try < 2);
     // Starting with MongoDB 3.2, this command returns code 20 when a collection is already sharded.
     // For older MongoDB versions, check the error message
     if ($result['ok'] == 1 || isset($result['code']) && $result['code'] == 20 || $result['errmsg'] == 'already sharded') {
         return;
     }
     throw MongoDBException::failedToEnsureDocumentSharding($documentName, $result['errmsg']);
 }
 private function loadReferenceManyCollection(PersistentCollection $collection)
 {
     $mapping = $collection->getMapping();
     $cmd = $this->cmd;
     $groupedIds = array();
     foreach ($collection->getMongoData() as $reference) {
         $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference);
         $mongoId = $reference[$cmd . 'id'];
         $id = (string) $mongoId;
         $reference = $this->dm->getReference($className, $id);
         $collection->add($reference);
         if ($reference instanceof Proxy && !$reference->__isInitialized__) {
             if (!isset($groupedIds[$className])) {
                 $groupedIds[$className] = array();
             }
             $groupedIds[$className][] = $mongoId;
         }
     }
     foreach ($groupedIds as $className => $ids) {
         $class = $this->dm->getClassMetadata($className);
         $mongoCollection = $this->dm->getDocumentCollection($className);
         $data = $mongoCollection->find(array('_id' => array($cmd . 'in' => $ids)));
         foreach ($data as $documentData) {
             $document = $this->uow->getById((string) $documentData['_id'], $class->rootDocumentName);
             $data = $this->hydratorFactory->hydrate($document, $documentData);
             $this->uow->setOriginalDocumentData($document, $data);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function write(array $products)
 {
     $this->collection = $this->documentManager->getDocumentCollection($this->productClass);
     $productsToInsert = [];
     $productsToUpdate = [];
     foreach ($products as $product) {
         if (null === $product->getId()) {
             $productsToInsert[] = $product;
             $product->setId($this->mongoFactory->createMongoId());
         } else {
             $productsToUpdate[] = $product;
         }
     }
     $this->eventDispatcher->dispatch(self::PRE_INSERT, new GenericEvent($productsToInsert));
     $this->eventDispatcher->dispatch(self::PRE_UPDATE, new GenericEvent($productsToUpdate));
     $insertDocs = $this->getDocsFromProducts($productsToInsert);
     $updateDocs = $this->getDocsFromProducts($productsToUpdate);
     if (count($insertDocs) > 0) {
         $this->insertDocuments($insertDocs);
     }
     if (count($updateDocs) > 0) {
         $this->updateDocuments($updateDocs);
     }
     $this->pendingPersister->persistPendingVersions($products);
     $this->eventDispatcher->dispatch(self::POST_INSERT, new GenericEvent($productsToInsert));
     $this->eventDispatcher->dispatch(self::POST_UPDATE, new GenericEvent($productsToUpdate));
     $this->documentManager->clear();
     $this->cacheClearer->clear();
 }
示例#13
0
 /**
  * Delete the given document's indexes.
  *
  * @param string $documentName
  * @throws \InvalidArgumentException
  */
 public function deleteDocumentIndexes($documentName)
 {
     $class = $this->dm->getClassMetadata($documentName);
     if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
         throw new \InvalidArgumentException('Cannot delete document indexes for mapped super classes or embedded documents.');
     }
     $this->dm->getDocumentCollection($documentName)->deleteIndexes();
 }
 /**
  * Executes a query updating the given document.
  *
  * @param object $document
  * @param array  $query
  * @param array  $options
  */
 private function executeQuery($document, array $query, array $options)
 {
     $className = get_class($document);
     $class = $this->dm->getClassMetadata($className);
     $findQuery = $this->getQueryForDocument($class, $document);
     $collection = $this->dm->getDocumentCollection($className);
     $collection->update($findQuery, $query, $options);
 }
 /**
  * Initializes a new BasicDocumentPersister instance.
  *
  * @param Doctrine\ODM\MongoDB\DocumentManager $dm
  * @param Doctrine\ODM\MongoDB\Mapping\ClassMetadata $class
  */
 public function __construct(DocumentManager $dm, ClassMetadata $class)
 {
     $this->_dm = $dm;
     $this->_uow = $dm->getUnitOfWork();
     $this->_class = $class;
     $this->_documentName = $class->getName();
     $this->_collection = $dm->getDocumentCollection($class->name);
 }
 /**
  * Executes a query updating the given document.
  *
  * @param object $document
  * @param array $query
  * @param array $options
  */
 private function executeQuery($document, array $query, array $options)
 {
     $className = get_class($document);
     $class = $this->dm->getClassMetadata($className);
     $id = $class->getDatabaseIdentifierValue($this->uow->getDocumentIdentifier($document));
     $collection = $this->dm->getDocumentCollection($className);
     $collection->update(array('_id' => $id), $query, $options);
 }
 /**
  * Get the last available version for the provided document
  *
  * @param VersionableInterface $versionable
  *
  * @return Version
  */
 protected function getPreviousVersion(VersionableInterface $versionable)
 {
     $versionCollection = $this->documentManager->getDocumentCollection($this->versionClass);
     $resourceName = get_class($versionable);
     $resourceId = $versionable->getId();
     $version = $this->documentManager->createQueryBuilder($this->versionClass)->field('resourceName')->equals($resourceName)->field('resourceId')->equals($resourceId)->limit(1)->sort('loggedAt', 'desc')->getQuery()->getSingleResult();
     return $version;
 }
示例#18
0
 private function loadReferenceManyCollectionOwningSide(PersistentCollection $collection)
 {
     $hints = $collection->getHints();
     $mapping = $collection->getMapping();
     $cmd = $this->cmd;
     $groupedIds = array();
     foreach ($collection->getMongoData() as $key => $reference) {
         if (isset($mapping['simple']) && $mapping['simple']) {
             $className = $mapping['targetDocument'];
             $mongoId = $reference;
         } else {
             $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference);
             $mongoId = $reference[$cmd . 'id'];
         }
         $id = (string) $mongoId;
         if (!$id) {
             continue;
         }
         $reference = $this->dm->getReference($className, $id);
         if ($mapping['strategy'] === 'set') {
             $collection->set($key, $reference);
         } else {
             $collection->add($reference);
         }
         if ($reference instanceof Proxy && !$reference->__isInitialized__) {
             if (!isset($groupedIds[$className])) {
                 $groupedIds[$className] = array();
             }
             $groupedIds[$className][] = $mongoId;
         }
     }
     foreach ($groupedIds as $className => $ids) {
         $class = $this->dm->getClassMetadata($className);
         $mongoCollection = $this->dm->getDocumentCollection($className);
         $criteria = array_merge(array('_id' => array($cmd . 'in' => $ids)), $this->dm->getFilterCollection()->getFilterCriteria($class), isset($mapping['criteria']) ? $mapping['criteria'] : array());
         $cursor = $mongoCollection->find($criteria);
         if (isset($mapping['sort'])) {
             $cursor->sort($mapping['sort']);
         }
         if (isset($mapping['limit'])) {
             $cursor->limit($mapping['limit']);
         }
         if (isset($mapping['skip'])) {
             $cursor->skip($mapping['skip']);
         }
         if (isset($hints[Query::HINT_SLAVE_OKAY])) {
             $cursor->slaveOkay(true);
         }
         $documents = $cursor->toArray();
         foreach ($documents as $documentData) {
             $document = $this->uow->getById((string) $documentData['_id'], $class->rootDocumentName);
             $data = $this->hydratorFactory->hydrate($document, $documentData);
             $this->uow->setOriginalDocumentData($document, $data);
             $document->__isInitialized__ = true;
         }
     }
 }
 /**
  * Find all common attribute ids with values from a list of product ids
  * Only exists for ODM repository
  *
  * @param array $productIds
  *
  * @return array
  */
 protected function findValuesCommonAttributeIds(array $productIds)
 {
     $collection = $this->dm->getDocumentCollection($this->documentName);
     $expr = new Expr($this->dm);
     $class = $this->dm->getClassMetadata($this->documentName);
     $expr->setClassMetadata($class);
     $expr->field('_id')->in($productIds);
     $pipeline = [['$match' => $expr->getQuery()], ['$unwind' => '$values'], ['$group' => ['_id' => ['id' => '$_id', 'family' => '$family'], 'attribute' => ['$addToSet' => '$values.attribute']]]];
     return $collection->aggregate($pipeline)->toArray();
 }
 /**
  * Gets or creates a Persister instance for the given class name.
  *
  * @param string $className
  * @return Persister $persister
  */
 public function getDocumentPersister($className)
 {
     if (isset($this->persisters[$className])) {
         return $this->persisters[$className];
     }
     $class = $this->dm->getClassMetadata($className);
     $collection = $this->dm->getDocumentCollection($className);
     $persister = $this->dm->getUnitOfWork()->getDocumentPersister($className);
     $this->persisters[$className] = new Persister($this->configuration, $class, $collection, $persister);
     return $this->persisters[$className];
 }
示例#21
0
 private function setDocumentName($documentName)
 {
     if (is_array($documentName)) {
         $documentNames = $documentName;
         $documentName = $documentNames[0];
         $discriminatorField = $this->dm->getClassMetadata($documentName)->discriminatorField['name'];
         $discriminatorValues = $this->getDiscriminatorValues($documentNames);
         $this->field($discriminatorField)->in($discriminatorValues);
     }
     if ($documentName !== null) {
         $this->collection = $this->dm->getDocumentCollection($documentName);
         $this->database = $this->collection->getDatabase();
         $this->class = $this->dm->getClassMetadata($documentName);
     }
 }
 /**
  * Executes a query updating the given document.
  *
  * @param object $document
  * @param array $newObj
  * @param array $options
  */
 private function executeQuery($document, array $newObj, array $options)
 {
     $className = get_class($document);
     $class = $this->dm->getClassMetadata($className);
     $id = $class->getDatabaseIdentifierValue($this->uow->getDocumentIdentifier($document));
     $query = array('_id' => $id);
     if ($class->isVersioned) {
         $query[$class->versionField] = $class->reflFields[$class->versionField]->getValue($document);
     }
     $collection = $this->dm->getDocumentCollection($className);
     $result = $collection->update($query, $newObj, $options);
     if ($class->isVersioned && !$result['n']) {
         throw LockException::lockFailed($document);
     }
 }
示例#23
0
文件: Builder.php 项目: im286er/ent
 /**
  * @param string[]|string $documentName an array of document names or just one.
  */
 private function setDocumentName($documentName)
 {
     if (is_array($documentName)) {
         $documentNames = $documentName;
         $documentName = $documentNames[0];
         $discriminatorField = $this->dm->getClassMetadata($documentName)->discriminatorField;
         $discriminatorValues = $this->getDiscriminatorValues($documentNames);
         $this->field($discriminatorField)->in($discriminatorValues);
     }
     if ($documentName !== null) {
         $this->collection = $this->dm->getDocumentCollection($documentName);
         $this->class = $this->dm->getClassMetadata($documentName);
         // Expr also needs to know
         $this->expr->setClassMetadata($this->class);
     }
 }
 /** @inheritDoc */
 public function generate(DocumentManager $dm, $document)
 {
     $className = get_class($document);
     $db = $dm->getDocumentDatabase($className);
     $coll = $dm->getDocumentCollection($className);
     $query = array('_id' => $coll->getName());
     $newObj = array('$inc' => array('current_id' => 1));
     $command = array();
     $command['findandmodify'] = 'doctrine_increment_ids';
     $command['query'] = $query;
     $command['update'] = $newObj;
     $command['upsert'] = true;
     $command['new'] = true;
     $result = $db->command($command);
     return $result['value']['current_id'];
 }
 private function initialize()
 {
     if (!$this->initialized) {
         if ($this->isDirty) {
             // Has NEW objects added through add(). Remember them.
             $newObjects = $this->coll->toArray();
         }
         $this->coll->clear();
         $groupedIds = array();
         foreach ($this->references as $reference) {
             $className = $this->dm->getClassNameFromDiscriminatorValue($this->mapping, $reference);
             if (!isset($groupedIds[$className])) {
                 $groupedIds[$className] = array();
             }
             $id = $reference[$this->cmd . 'id'];
             $groupedIds[$className][] = $id;
             $reference = $this->dm->getReference($className, (string) $id);
             $this->add($reference);
         }
         foreach ($groupedIds as $className => $ids) {
             $collection = $this->dm->getDocumentCollection($className);
             $data = $collection->find(array('_id' => array($this->cmd . 'in' => $ids)));
             $hints = array(Query::HINT_REFRESH => Query::HINT_REFRESH);
             foreach ($data as $id => $documentData) {
                 $document = $this->dm->getUnitOfWork()->getOrCreateDocument($className, $documentData, $hints);
                 if ($document instanceof Proxy) {
                     $document->__isInitialized__ = true;
                     unset($document->__dm);
                     unset($document->__identifier);
                 }
             }
         }
         $this->takeSnapshot();
         // Reattach NEW objects added through add(), if any.
         if (isset($newObjects)) {
             foreach ($newObjects as $obj) {
                 $this->coll->add($obj);
             }
             $this->isDirty = true;
         }
         $this->initialized = true;
     }
 }
示例#26
0
 /**
  * @param string[]|string $documentName an array of document names or just one.
  */
 private function setDocumentName($documentName)
 {
     if (is_array($documentName)) {
         $documentNames = $documentName;
         $documentName = $documentNames[0];
         $metadata = $this->dm->getClassMetadata($documentName);
         $discriminatorField = $metadata->discriminatorField;
         $discriminatorValues = $this->getDiscriminatorValues($documentNames);
         // If a defaultDiscriminatorValue is set and it is among the discriminators being queries, add NULL to the list
         if ($metadata->defaultDiscriminatorValue && array_search($metadata->defaultDiscriminatorValue, $discriminatorValues) !== false) {
             $discriminatorValues[] = null;
         }
         $this->field($discriminatorField)->in($discriminatorValues);
     }
     if ($documentName !== null) {
         $this->collection = $this->dm->getDocumentCollection($documentName);
         $this->class = $this->dm->getClassMetadata($documentName);
         // Expr also needs to know
         $this->expr->setClassMetadata($this->class);
     }
 }
示例#27
0
 /**
  * Ensure sharding for collection by document name.
  *
  * @param string $documentName
  * @param array  $indexOptions Options for `ensureIndex` command. It's performed on an existing collections.
  *
  * @throws MongoDBException
  */
 public function ensureDocumentSharding($documentName, array $indexOptions = array())
 {
     $class = $this->dm->getClassMetadata($documentName);
     if (!$class->isSharded()) {
         return;
     }
     $this->enableShardingForDbByDocumentName($documentName);
     do {
         $result = $this->runShardCollectionCommand($documentName);
         $done = true;
         $try = 0;
         if ($result['ok'] != 1 && isset($result['proposedKey'])) {
             $this->dm->getDocumentCollection($documentName)->ensureIndex($result['proposedKey'], $indexOptions);
             $done = false;
             $try++;
         }
     } while (!$done && $try < 2);
     if ($result['ok'] != 1 && $result['errmsg'] !== 'already sharded') {
         throw MongoDBException::failedToEnsureDocumentSharding($documentName, $result['errmsg']);
     }
 }
示例#28
0
 /**
  * @param PersistentCollection $collection
  * @param array $groupedIds
  *
  * @throws \Doctrine\ODM\MongoDB\MongoDBException
  */
 private function loadActualDataForSortedReferenceManyCollectionByIds(PersistentCollection $collection, array $groupedIds)
 {
     $mapping = $collection->getMapping();
     $hints = $collection->getHints();
     foreach ($groupedIds as $className => $ids) {
         $class = $this->dm->getClassMetadata($className);
         $mongoCollection = $this->dm->getDocumentCollection($className);
         $criteria = $this->cm->merge(array('_id' => array('$in' => array_values($ids))), $this->dm->getFilterCollection()->getFilterCriteria($class), isset($mapping['criteria']) ? $mapping['criteria'] : array());
         $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria);
         $cursor = $mongoCollection->find($criteria);
         if (isset($mapping['sort'])) {
             $cursor->sort($mapping['sort']);
         }
         if (isset($mapping['limit'])) {
             $cursor->limit($mapping['limit']);
         }
         if (isset($mapping['skip'])) {
             $cursor->skip($mapping['skip']);
         }
         if (!empty($hints[Query::HINT_SLAVE_OKAY])) {
             $cursor->slaveOkay(true);
         }
         if (!empty($hints[Query::HINT_READ_PREFERENCE])) {
             $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]);
         }
         $documents = $cursor->toArray(false);
         foreach ($documents as $documentData) {
             $docId = $documentData['_id'];
             $document = $this->uow->getById($docId, $class);
             $data = $this->hydratorFactory->hydrate($document, $documentData);
             $this->uow->setOriginalDocumentData($document, $data);
             $document->__isInitialized__ = true;
             $collection->add($document);
         }
     }
 }
示例#29
0
 private function loadReferenceManyCollectionOwningSide(PersistentCollection $collection)
 {
     $hints = $collection->getHints();
     $mapping = $collection->getMapping();
     $groupedIds = array();
     $sorted = isset($mapping['sort']) && $mapping['sort'];
     foreach ($collection->getMongoData() as $key => $reference) {
         if (isset($mapping['simple']) && $mapping['simple']) {
             $className = $mapping['targetDocument'];
             $mongoId = $reference;
         } else {
             $className = $this->uow->getClassNameForAssociation($mapping, $reference);
             $mongoId = $reference['$id'];
         }
         $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($mongoId);
         // create a reference to the class and id
         $reference = $this->dm->getReference($className, $id);
         // no custom sort so add the references right now in the order they are embedded
         if (!$sorted) {
             if (CollectionHelper::isHash($mapping['strategy'])) {
                 $collection->set($key, $reference);
             } else {
                 $collection->add($reference);
             }
         }
         // only query for the referenced object if it is not already initialized or the collection is sorted
         if ($reference instanceof Proxy && !$reference->__isInitialized__ || $sorted) {
             $groupedIds[$className][] = $mongoId;
         }
     }
     foreach ($groupedIds as $className => $ids) {
         $class = $this->dm->getClassMetadata($className);
         $mongoCollection = $this->dm->getDocumentCollection($className);
         $criteria = $this->cm->merge(array('_id' => array('$in' => array_values($ids))), $this->dm->getFilterCollection()->getFilterCriteria($class), isset($mapping['criteria']) ? $mapping['criteria'] : array());
         $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria);
         $cursor = $mongoCollection->find($criteria);
         if (isset($mapping['sort'])) {
             $cursor->sort($mapping['sort']);
         }
         if (isset($mapping['limit'])) {
             $cursor->limit($mapping['limit']);
         }
         if (isset($mapping['skip'])) {
             $cursor->skip($mapping['skip']);
         }
         if (!empty($hints[Query::HINT_SLAVE_OKAY])) {
             $cursor->slaveOkay(true);
         }
         if (!empty($hints[Query::HINT_READ_PREFERENCE])) {
             $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]);
         }
         $documents = $cursor->toArray(false);
         foreach ($documents as $documentData) {
             $document = $this->uow->getById($documentData['_id'], $class);
             $data = $this->hydratorFactory->hydrate($document, $documentData);
             $this->uow->setOriginalDocumentData($document, $data);
             $document->__isInitialized__ = true;
             if ($sorted) {
                 $collection->add($document);
             }
         }
     }
 }
示例#30
0
 /**
  * Initializes a new DocumentPersister instance.
  *
  * @param Doctrine\ODM\MongoDB\Persisters\PersistenceBuilder $pb
  * @param Doctrine\ODM\MongoDB\DocumentManager $dm
  * @param Doctrine\Common\EventManager $evm
  * @param Doctrine\ODM\MongoDB\UnitOfWork $uow
  * @param Doctrine\ODM\MongoDB\Hydrator\HydratorFactory $hydratorFactory
  * @param Doctrine\ODM\MongoDB\Mapping\ClassMetadata $class
  * @param string $cmd
  */
 public function __construct(PersistenceBuilder $pb, DocumentManager $dm, EventManager $evm, UnitOfWork $uow, HydratorFactory $hydratorFactory, ClassMetadata $class, $cmd)
 {
     $this->pb = $pb;
     $this->dm = $dm;
     $this->evm = $evm;
     $this->cmd = $cmd;
     $this->uow = $uow;
     $this->hydratorFactory = $hydratorFactory;
     $this->class = $class;
     $this->collection = $dm->getDocumentCollection($class->name);
 }