Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like DocumentPersister often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DocumentPersister, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
46 | class DocumentPersister |
||
47 | { |
||
48 | /** |
||
49 | * The PersistenceBuilder instance. |
||
50 | * |
||
51 | * @var PersistenceBuilder |
||
52 | */ |
||
53 | private $pb; |
||
54 | |||
55 | /** |
||
56 | * The DocumentManager instance. |
||
57 | * |
||
58 | * @var DocumentManager |
||
59 | */ |
||
60 | private $dm; |
||
61 | |||
62 | /** |
||
63 | * The EventManager instance |
||
64 | * |
||
65 | * @var EventManager |
||
66 | */ |
||
67 | private $evm; |
||
68 | |||
69 | /** |
||
70 | * The UnitOfWork instance. |
||
71 | * |
||
72 | * @var UnitOfWork |
||
73 | */ |
||
74 | private $uow; |
||
75 | |||
76 | /** |
||
77 | * The ClassMetadata instance for the document type being persisted. |
||
78 | * |
||
79 | * @var ClassMetadata |
||
80 | */ |
||
81 | private $class; |
||
82 | |||
83 | /** |
||
84 | * The MongoCollection instance for this document. |
||
85 | * |
||
86 | * @var \MongoCollection |
||
87 | */ |
||
88 | private $collection; |
||
89 | |||
90 | /** |
||
91 | * Array of queued inserts for the persister to insert. |
||
92 | * |
||
93 | * @var array |
||
94 | */ |
||
95 | private $queuedInserts = array(); |
||
96 | |||
97 | /** |
||
98 | * Array of queued inserts for the persister to insert. |
||
99 | * |
||
100 | * @var array |
||
101 | */ |
||
102 | private $queuedUpserts = array(); |
||
103 | |||
104 | /** |
||
105 | * The CriteriaMerger instance. |
||
106 | * |
||
107 | * @var CriteriaMerger |
||
108 | */ |
||
109 | private $cm; |
||
110 | |||
111 | /** |
||
112 | * The CollectionPersister instance. |
||
113 | * |
||
114 | * @var CollectionPersister |
||
115 | */ |
||
116 | private $cp; |
||
117 | |||
118 | /** |
||
119 | * Initializes this instance. |
||
120 | * |
||
121 | * @param PersistenceBuilder $pb |
||
122 | * @param DocumentManager $dm |
||
123 | * @param EventManager $evm |
||
124 | * @param UnitOfWork $uow |
||
125 | * @param HydratorFactory $hydratorFactory |
||
126 | * @param ClassMetadata $class |
||
127 | * @param CriteriaMerger $cm |
||
128 | */ |
||
129 | 760 | public function __construct( |
|
130 | PersistenceBuilder $pb, |
||
131 | DocumentManager $dm, |
||
132 | EventManager $evm, |
||
133 | UnitOfWork $uow, |
||
134 | HydratorFactory $hydratorFactory, |
||
135 | ClassMetadata $class, |
||
136 | CriteriaMerger $cm = null |
||
137 | ) { |
||
138 | 760 | $this->pb = $pb; |
|
139 | 760 | $this->dm = $dm; |
|
140 | 760 | $this->evm = $evm; |
|
141 | 760 | $this->cm = $cm ?: new CriteriaMerger(); |
|
142 | 760 | $this->uow = $uow; |
|
143 | 760 | $this->hydratorFactory = $hydratorFactory; |
|
|
|||
144 | 760 | $this->class = $class; |
|
145 | 760 | $this->collection = $dm->getDocumentCollection($class->name); |
|
146 | 760 | $this->cp = $this->uow->getCollectionPersister(); |
|
147 | 760 | } |
|
148 | |||
149 | /** |
||
150 | * @return array |
||
151 | */ |
||
152 | public function getInserts() |
||
156 | |||
157 | /** |
||
158 | * @param object $document |
||
159 | * @return bool |
||
160 | */ |
||
161 | public function isQueuedForInsert($document) |
||
165 | |||
166 | /** |
||
167 | * Adds a document to the queued insertions. |
||
168 | * The document remains queued until {@link executeInserts} is invoked. |
||
169 | * |
||
170 | * @param object $document The document to queue for insertion. |
||
171 | */ |
||
172 | 532 | public function addInsert($document) |
|
176 | |||
177 | /** |
||
178 | * @return array |
||
179 | */ |
||
180 | public function getUpserts() |
||
184 | |||
185 | /** |
||
186 | * @param object $document |
||
187 | * @return boolean |
||
188 | */ |
||
189 | public function isQueuedForUpsert($document) |
||
193 | |||
194 | /** |
||
195 | * Adds a document to the queued upserts. |
||
196 | * The document remains queued until {@link executeUpserts} is invoked. |
||
197 | * |
||
198 | * @param object $document The document to queue for insertion. |
||
199 | */ |
||
200 | 87 | public function addUpsert($document) |
|
204 | |||
205 | /** |
||
206 | * Gets the ClassMetadata instance of the document class this persister is used for. |
||
207 | * |
||
208 | * @return ClassMetadata |
||
209 | */ |
||
210 | public function getClassMetadata() |
||
214 | |||
215 | /** |
||
216 | * Executes all queued document insertions. |
||
217 | * |
||
218 | * Queued documents without an ID will inserted in a batch and queued |
||
219 | * documents with an ID will be upserted individually. |
||
220 | * |
||
221 | * If no inserts are queued, invoking this method is a NOOP. |
||
222 | * |
||
223 | * @param array $options Options for batchInsert() and update() driver methods |
||
224 | */ |
||
225 | 532 | public function executeInserts(array $options = array()) |
|
226 | { |
||
227 | 532 | if ( ! $this->queuedInserts) { |
|
228 | return; |
||
229 | } |
||
230 | |||
231 | 532 | $inserts = array(); |
|
232 | 532 | $options = $this->getWriteOptions($options); |
|
233 | 532 | foreach ($this->queuedInserts as $oid => $document) { |
|
234 | 532 | $data = $this->pb->prepareInsertData($document); |
|
235 | |||
236 | // Set the initial version for each insert |
||
237 | 531 | View Code Duplication | if ($this->class->isVersioned) { |
238 | 39 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
239 | 39 | if ($versionMapping['type'] === 'int') { |
|
240 | 37 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
241 | 37 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
242 | 2 | } elseif ($versionMapping['type'] === 'date') { |
|
243 | 2 | $nextVersionDateTime = new \DateTime(); |
|
244 | 2 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
245 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
246 | } |
||
247 | 39 | $data[$versionMapping['name']] = $nextVersion; |
|
248 | } |
||
249 | |||
250 | 531 | $inserts[$oid] = $data; |
|
251 | } |
||
252 | |||
253 | 531 | if ($inserts) { |
|
254 | try { |
||
255 | 531 | $this->collection->batchInsert($inserts, $options); |
|
256 | 7 | } catch (\MongoException $e) { |
|
257 | 7 | $this->queuedInserts = array(); |
|
258 | 7 | throw $e; |
|
259 | } |
||
260 | } |
||
261 | |||
262 | /* All collections except for ones using addToSet have already been |
||
263 | * saved. We have left these to be handled separately to avoid checking |
||
264 | * collection for uniqueness on PHP side. |
||
265 | */ |
||
266 | 531 | foreach ($this->queuedInserts as $document) { |
|
267 | 531 | $this->handleCollections($document, $options); |
|
268 | } |
||
269 | |||
270 | 531 | $this->queuedInserts = array(); |
|
271 | 531 | } |
|
272 | |||
273 | /** |
||
274 | * Executes all queued document upserts. |
||
275 | * |
||
276 | * Queued documents with an ID are upserted individually. |
||
277 | * |
||
278 | * If no upserts are queued, invoking this method is a NOOP. |
||
279 | * |
||
280 | * @param array $options Options for batchInsert() and update() driver methods |
||
281 | */ |
||
282 | 87 | public function executeUpserts(array $options = array()) |
|
283 | { |
||
284 | 87 | if ( ! $this->queuedUpserts) { |
|
285 | return; |
||
286 | } |
||
287 | |||
288 | 87 | $options = $this->getWriteOptions($options); |
|
289 | 87 | foreach ($this->queuedUpserts as $oid => $document) { |
|
290 | try { |
||
291 | 87 | $this->executeUpsert($document, $options); |
|
292 | 87 | $this->handleCollections($document, $options); |
|
293 | 87 | unset($this->queuedUpserts[$oid]); |
|
294 | } catch (\MongoException $e) { |
||
295 | unset($this->queuedUpserts[$oid]); |
||
296 | 87 | throw $e; |
|
297 | } |
||
298 | } |
||
299 | 87 | } |
|
300 | |||
301 | /** |
||
302 | * Executes a single upsert in {@link executeUpserts} |
||
303 | * |
||
304 | * @param object $document |
||
305 | * @param array $options |
||
306 | */ |
||
307 | 87 | private function executeUpsert($document, array $options) |
|
308 | { |
||
309 | 87 | $options['upsert'] = true; |
|
310 | 87 | $criteria = $this->getQueryForDocument($document); |
|
311 | |||
312 | 87 | $data = $this->pb->prepareUpsertData($document); |
|
313 | |||
314 | // Set the initial version for each upsert |
||
315 | 87 | View Code Duplication | if ($this->class->isVersioned) { |
316 | 3 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
317 | 3 | if ($versionMapping['type'] === 'int') { |
|
318 | 2 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
319 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
320 | 1 | } elseif ($versionMapping['type'] === 'date') { |
|
321 | 1 | $nextVersionDateTime = new \DateTime(); |
|
322 | 1 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
323 | 1 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
324 | } |
||
325 | 3 | $data['$set'][$versionMapping['name']] = $nextVersion; |
|
326 | } |
||
327 | |||
328 | 87 | foreach (array_keys($criteria) as $field) { |
|
329 | 87 | unset($data['$set'][$field]); |
|
330 | } |
||
331 | |||
332 | // Do not send an empty $set modifier |
||
333 | 87 | if (empty($data['$set'])) { |
|
334 | 17 | unset($data['$set']); |
|
335 | } |
||
336 | |||
337 | /* If there are no modifiers remaining, we're upserting a document with |
||
338 | * an identifier as its only field. Since a document with the identifier |
||
339 | * may already exist, the desired behavior is "insert if not exists" and |
||
340 | * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set |
||
341 | * the identifier to the same value in our criteria. |
||
342 | * |
||
343 | * This will fail for versions before MongoDB 2.6, which require an |
||
344 | * empty $set modifier. The best we can do (without attempting to check |
||
345 | * server versions in advance) is attempt the 2.6+ behavior and retry |
||
346 | * after the relevant exception. |
||
347 | * |
||
348 | * See: https://jira.mongodb.org/browse/SERVER-12266 |
||
349 | */ |
||
350 | 87 | if (empty($data)) { |
|
351 | 17 | $retry = true; |
|
352 | 17 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
353 | } |
||
354 | |||
355 | try { |
||
356 | 87 | $this->collection->update($criteria, $data, $options); |
|
357 | 87 | return; |
|
358 | } catch (\MongoCursorException $e) { |
||
359 | if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) { |
||
360 | throw $e; |
||
361 | } |
||
362 | } |
||
363 | |||
364 | $this->collection->update($criteria, array('$set' => new \stdClass), $options); |
||
365 | } |
||
366 | |||
367 | /** |
||
368 | * Updates the already persisted document if it has any new changesets. |
||
369 | * |
||
370 | * @param object $document |
||
371 | * @param array $options Array of options to be used with update() |
||
372 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
373 | */ |
||
374 | 225 | public function update($document, array $options = array()) |
|
375 | { |
||
376 | 225 | $update = $this->pb->prepareUpdateData($document); |
|
377 | |||
378 | 225 | $query = $this->getQueryForDocument($document); |
|
379 | |||
380 | 223 | foreach (array_keys($query) as $field) { |
|
381 | 223 | unset($update['$set'][$field]); |
|
382 | } |
||
383 | |||
384 | 223 | if (empty($update['$set'])) { |
|
385 | 94 | unset($update['$set']); |
|
386 | } |
||
387 | |||
388 | |||
389 | // Include versioning logic to set the new version value in the database |
||
390 | // and to ensure the version has not changed since this document object instance |
||
391 | // was fetched from the database |
||
392 | 223 | if ($this->class->isVersioned) { |
|
393 | 31 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
394 | 31 | $currentVersion = $this->class->reflFields[$this->class->versionField]->getValue($document); |
|
395 | 31 | if ($versionMapping['type'] === 'int') { |
|
396 | 28 | $nextVersion = $currentVersion + 1; |
|
397 | 28 | $update['$inc'][$versionMapping['name']] = 1; |
|
398 | 28 | $query[$versionMapping['name']] = $currentVersion; |
|
399 | 28 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
400 | 3 | } elseif ($versionMapping['type'] === 'date') { |
|
401 | 3 | $nextVersion = new \DateTime(); |
|
402 | 3 | $update['$set'][$versionMapping['name']] = new \MongoDate($nextVersion->getTimestamp()); |
|
403 | 3 | $query[$versionMapping['name']] = new \MongoDate($currentVersion->getTimestamp()); |
|
404 | 3 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
405 | } |
||
406 | } |
||
407 | |||
408 | 223 | if ( ! empty($update)) { |
|
409 | // Include locking logic so that if the document object in memory is currently |
||
410 | // locked then it will remove it, otherwise it ensures the document is not locked. |
||
411 | 155 | if ($this->class->isLockable) { |
|
412 | 11 | $isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document); |
|
413 | 11 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
414 | 11 | if ($isLocked) { |
|
415 | 2 | $update['$unset'] = array($lockMapping['name'] => true); |
|
416 | } else { |
||
417 | 9 | $query[$lockMapping['name']] = array('$exists' => false); |
|
418 | } |
||
419 | } |
||
420 | |||
421 | 155 | $options = $this->getWriteOptions($options); |
|
422 | |||
423 | 155 | $result = $this->collection->update($query, $update, $options); |
|
424 | |||
425 | 155 | View Code Duplication | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
426 | 5 | throw LockException::lockFailed($document); |
|
427 | } |
||
428 | } |
||
429 | |||
430 | 219 | $this->handleCollections($document, $options); |
|
431 | 219 | } |
|
432 | |||
433 | /** |
||
434 | * Removes document from mongo |
||
435 | * |
||
436 | * @param mixed $document |
||
437 | * @param array $options Array of options to be used with remove() |
||
438 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
439 | */ |
||
440 | 34 | public function delete($document, array $options = array()) |
|
441 | { |
||
442 | 34 | $query = $this->getQueryForDocument($document); |
|
443 | |||
444 | 34 | if ($this->class->isLockable) { |
|
445 | 2 | $query[$this->class->lockField] = array('$exists' => false); |
|
446 | } |
||
447 | |||
448 | 34 | $options = $this->getWriteOptions($options); |
|
449 | |||
450 | 34 | $result = $this->collection->remove($query, $options); |
|
451 | |||
452 | 34 | View Code Duplication | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
453 | 2 | throw LockException::lockFailed($document); |
|
454 | } |
||
455 | 32 | } |
|
456 | |||
457 | /** |
||
458 | * Refreshes a managed document. |
||
459 | * |
||
460 | * @param string $id |
||
461 | * @param object $document The document to refresh. |
||
462 | * |
||
463 | * @deprecated The first argument is deprecated. |
||
464 | */ |
||
465 | 21 | public function refresh($id, $document) |
|
466 | { |
||
467 | 21 | $query = $this->getQueryForDocument($document); |
|
468 | 21 | $data = $this->collection->findOne($query); |
|
469 | 21 | $data = $this->hydratorFactory->hydrate($document, $data); |
|
470 | 21 | $this->uow->setOriginalDocumentData($document, $data); |
|
471 | 21 | } |
|
472 | |||
473 | /** |
||
474 | * Finds a document by a set of criteria. |
||
475 | * |
||
476 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
477 | * match an _id value. |
||
478 | * |
||
479 | * @param mixed $criteria Query criteria |
||
480 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
481 | * @param array $hints Hints for document creation |
||
482 | * @param integer $lockMode |
||
483 | * @param array $sort Sort array for Cursor::sort() |
||
484 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
485 | * @return object|null The loaded and managed document instance or null if no document was found |
||
486 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
487 | */ |
||
488 | 376 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
516 | |||
517 | /** |
||
518 | * Finds documents by a set of criteria. |
||
519 | * |
||
520 | * @param array $criteria Query criteria |
||
521 | * @param array $sort Sort array for Cursor::sort() |
||
522 | * @param integer|null $limit Limit for Cursor::limit() |
||
523 | * @param integer|null $skip Skip for Cursor::skip() |
||
524 | * @return Cursor |
||
525 | */ |
||
526 | 23 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
549 | |||
550 | /** |
||
551 | * @param object $document |
||
552 | * |
||
553 | * @return array |
||
554 | * @throws MongoDBException |
||
555 | */ |
||
556 | 302 | private function getShardKeyQuery($document) |
|
557 | { |
||
558 | 302 | if ( ! $this->class->isSharded()) { |
|
559 | 293 | return array(); |
|
560 | } |
||
561 | |||
562 | 9 | $shardKey = $this->class->getShardKey(); |
|
563 | 9 | $keys = array_keys($shardKey['keys']); |
|
564 | 9 | $data = $this->uow->getDocumentActualData($document); |
|
565 | |||
566 | 9 | $shardKeyQueryPart = array(); |
|
567 | 9 | foreach ($keys as $key) { |
|
568 | 9 | $mapping = $this->class->getFieldMappingByDbFieldName($key); |
|
569 | 9 | $this->guardMissingShardKey($document, $key, $data); |
|
570 | 7 | $value = Type::getType($mapping['type'])->convertToDatabaseValue($data[$mapping['fieldName']]); |
|
571 | 7 | $shardKeyQueryPart[$key] = $value; |
|
572 | } |
||
573 | |||
574 | 7 | return $shardKeyQueryPart; |
|
575 | } |
||
576 | |||
577 | /** |
||
578 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
579 | * |
||
580 | * @param CursorInterface $baseCursor |
||
581 | * @return Cursor |
||
582 | */ |
||
583 | 23 | private function wrapCursor(CursorInterface $baseCursor) |
|
587 | |||
588 | /** |
||
589 | * Checks whether the given managed document exists in the database. |
||
590 | * |
||
591 | * @param object $document |
||
592 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
593 | */ |
||
594 | 3 | public function exists($document) |
|
599 | |||
600 | /** |
||
601 | * Locks document by storing the lock mode on the mapped lock field. |
||
602 | * |
||
603 | * @param object $document |
||
604 | * @param int $lockMode |
||
605 | */ |
||
606 | 5 | public function lock($document, $lockMode) |
|
614 | |||
615 | /** |
||
616 | * Releases any lock that exists on this document. |
||
617 | * |
||
618 | * @param object $document |
||
619 | */ |
||
620 | 1 | public function unlock($document) |
|
628 | |||
629 | /** |
||
630 | * Creates or fills a single document object from an query result. |
||
631 | * |
||
632 | * @param object $result The query result. |
||
633 | * @param object $document The document object to fill, if any. |
||
634 | * @param array $hints Hints for document creation. |
||
635 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
636 | */ |
||
637 | 375 | private function createDocument($result, $document = null, array $hints = array()) |
|
651 | |||
652 | /** |
||
653 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
654 | * |
||
655 | * @param PersistentCollectionInterface $collection |
||
656 | */ |
||
657 | 170 | public function loadCollection(PersistentCollectionInterface $collection) |
|
678 | |||
679 | 119 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
680 | { |
||
681 | 119 | $embeddedDocuments = $collection->getMongoData(); |
|
682 | 119 | $mapping = $collection->getMapping(); |
|
683 | 119 | $owner = $collection->getOwner(); |
|
684 | 119 | if ($embeddedDocuments) { |
|
685 | 90 | foreach ($embeddedDocuments as $key => $embeddedDocument) { |
|
686 | 90 | $className = $this->uow->getClassNameForAssociation($mapping, $embeddedDocument); |
|
687 | 90 | $embeddedMetadata = $this->dm->getClassMetadata($className); |
|
688 | 90 | $embeddedDocumentObject = $embeddedMetadata->newInstance(); |
|
689 | |||
690 | 90 | $this->uow->setParentAssociation($embeddedDocumentObject, $mapping, $owner, $mapping['name'] . '.' . $key); |
|
691 | |||
692 | 90 | $data = $this->hydratorFactory->hydrate($embeddedDocumentObject, $embeddedDocument, $collection->getHints()); |
|
693 | 90 | $id = $embeddedMetadata->identifier && isset($data[$embeddedMetadata->identifier]) |
|
694 | 23 | ? $data[$embeddedMetadata->identifier] |
|
695 | 90 | : null; |
|
696 | |||
697 | 90 | if (empty($collection->getHints()[Query::HINT_READ_ONLY])) { |
|
698 | 89 | $this->uow->registerManaged($embeddedDocumentObject, $id, $data); |
|
699 | } |
||
700 | 90 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
701 | 25 | $collection->set($key, $embeddedDocumentObject); |
|
702 | } else { |
||
703 | 90 | $collection->add($embeddedDocumentObject); |
|
704 | } |
||
705 | } |
||
706 | } |
||
707 | 119 | } |
|
708 | |||
709 | 55 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
710 | { |
||
711 | 55 | $hints = $collection->getHints(); |
|
712 | 55 | $mapping = $collection->getMapping(); |
|
713 | 55 | $groupedIds = array(); |
|
714 | |||
715 | 55 | $sorted = isset($mapping['sort']) && $mapping['sort']; |
|
716 | |||
717 | 55 | foreach ($collection->getMongoData() as $key => $reference) { |
|
718 | 50 | if (isset($mapping['storeAs']) && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID) { |
|
719 | 5 | $className = $mapping['targetDocument']; |
|
720 | 5 | $mongoId = $reference; |
|
721 | } else { |
||
722 | 46 | $className = $this->uow->getClassNameForAssociation($mapping, $reference); |
|
723 | 46 | $mongoId = $reference['$id']; |
|
724 | } |
||
725 | 50 | $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($mongoId); |
|
726 | |||
727 | // create a reference to the class and id |
||
728 | 50 | $reference = $this->dm->getReference($className, $id); |
|
729 | |||
730 | // no custom sort so add the references right now in the order they are embedded |
||
731 | 50 | if ( ! $sorted) { |
|
732 | 49 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
733 | 2 | $collection->set($key, $reference); |
|
734 | } else { |
||
735 | 47 | $collection->add($reference); |
|
736 | } |
||
737 | } |
||
738 | |||
739 | // only query for the referenced object if it is not already initialized or the collection is sorted |
||
740 | 50 | if (($reference instanceof Proxy && ! $reference->__isInitialized__) || $sorted) { |
|
741 | 50 | $groupedIds[$className][] = $mongoId; |
|
742 | } |
||
743 | } |
||
744 | 55 | foreach ($groupedIds as $className => $ids) { |
|
745 | 35 | $class = $this->dm->getClassMetadata($className); |
|
746 | 35 | $mongoCollection = $this->dm->getDocumentCollection($className); |
|
747 | 35 | $criteria = $this->cm->merge( |
|
748 | 35 | array('_id' => array('$in' => array_values($ids))), |
|
749 | 35 | $this->dm->getFilterCollection()->getFilterCriteria($class), |
|
750 | 35 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
751 | ); |
||
752 | 35 | $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); |
|
753 | 35 | $cursor = $mongoCollection->find($criteria); |
|
754 | 35 | if (isset($mapping['sort'])) { |
|
755 | 35 | $cursor->sort($mapping['sort']); |
|
756 | } |
||
757 | 35 | if (isset($mapping['limit'])) { |
|
758 | $cursor->limit($mapping['limit']); |
||
759 | } |
||
760 | 35 | if (isset($mapping['skip'])) { |
|
761 | $cursor->skip($mapping['skip']); |
||
762 | } |
||
763 | 35 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
764 | $cursor->slaveOkay(true); |
||
765 | } |
||
766 | 35 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
767 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
768 | } |
||
769 | 35 | $documents = $cursor->toArray(false); |
|
770 | 35 | foreach ($documents as $documentData) { |
|
771 | 34 | $document = $this->uow->getById($documentData['_id'], $class); |
|
772 | 34 | if ($document instanceof Proxy && ! $document->__isInitialized()) { |
|
773 | 34 | $data = $this->hydratorFactory->hydrate($document, $documentData); |
|
774 | 34 | $this->uow->setOriginalDocumentData($document, $data); |
|
775 | 34 | $document->__isInitialized__ = true; |
|
776 | } |
||
777 | 34 | if ($sorted) { |
|
778 | 35 | $collection->add($document); |
|
779 | } |
||
780 | } |
||
781 | } |
||
782 | 55 | } |
|
783 | |||
784 | 14 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
785 | { |
||
786 | 14 | $query = $this->createReferenceManyInverseSideQuery($collection); |
|
787 | 14 | $documents = $query->execute()->toArray(false); |
|
788 | 14 | foreach ($documents as $key => $document) { |
|
789 | 13 | $collection->add($document); |
|
790 | } |
||
791 | 14 | } |
|
792 | |||
793 | /** |
||
794 | * @param PersistentCollectionInterface $collection |
||
795 | * |
||
796 | * @return Query |
||
797 | */ |
||
798 | 16 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
834 | |||
835 | 3 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
848 | |||
849 | /** |
||
850 | * @param PersistentCollectionInterface $collection |
||
851 | * |
||
852 | * @return CursorInterface |
||
853 | */ |
||
854 | 3 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
884 | |||
885 | /** |
||
886 | * Prepare a sort or projection array by converting keys, which are PHP |
||
887 | * property names, to MongoDB field names. |
||
888 | * |
||
889 | * @param array $fields |
||
890 | * @return array |
||
891 | */ |
||
892 | 141 | public function prepareSortOrProjection(array $fields) |
|
902 | |||
903 | /** |
||
904 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
905 | * |
||
906 | * @param string $fieldName |
||
907 | * @return string |
||
908 | */ |
||
909 | 91 | public function prepareFieldName($fieldName) |
|
915 | |||
916 | /** |
||
917 | * Adds discriminator criteria to an already-prepared query. |
||
918 | * |
||
919 | * This method should be used once for query criteria and not be used for |
||
920 | * nested expressions. It should be called before |
||
921 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
922 | * |
||
923 | * @param array $preparedQuery |
||
924 | * @return array |
||
925 | */ |
||
926 | 527 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
942 | |||
943 | /** |
||
944 | * Adds filter criteria to an already-prepared query. |
||
945 | * |
||
946 | * This method should be used once for query criteria and not be used for |
||
947 | * nested expressions. It should be called after |
||
948 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
949 | * |
||
950 | * @param array $preparedQuery |
||
951 | * @return array |
||
952 | */ |
||
953 | 528 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
967 | |||
968 | /** |
||
969 | * Prepares the query criteria or new document object. |
||
970 | * |
||
971 | * PHP field names and types will be converted to those used by MongoDB. |
||
972 | * |
||
973 | * @param array $query |
||
974 | * @param bool $isNewObj |
||
975 | * @return array |
||
976 | */ |
||
977 | 553 | public function prepareQueryOrNewObj(array $query, $isNewObj = false) |
|
1005 | |||
1006 | /** |
||
1007 | * Prepares a query value and converts the PHP value to the database value |
||
1008 | * if it is an identifier. |
||
1009 | * |
||
1010 | * It also handles converting $fieldName to the database name if they are different. |
||
1011 | * |
||
1012 | * @param string $fieldName |
||
1013 | * @param mixed $value |
||
1014 | * @param ClassMetadata $class Defaults to $this->class |
||
1015 | * @param bool $prepareValue Whether or not to prepare the value |
||
1016 | * @param bool $inNewObj Whether or not newObj is being prepared |
||
1017 | * @return array An array of tuples containing prepared field names and values |
||
1018 | */ |
||
1019 | 547 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true, $inNewObj = false) |
|
1206 | |||
1207 | /** |
||
1208 | * Prepares a query expression. |
||
1209 | * |
||
1210 | * @param array|object $expression |
||
1211 | * @param ClassMetadata $class |
||
1212 | * @return array |
||
1213 | */ |
||
1214 | 69 | private function prepareQueryExpression($expression, $class) |
|
1241 | |||
1242 | /** |
||
1243 | * Checks whether the value has DBRef fields. |
||
1244 | * |
||
1245 | * This method doesn't check if the the value is a complete DBRef object, |
||
1246 | * although it should return true for a DBRef. Rather, we're checking that |
||
1247 | * the value has one or more fields for a DBref. In practice, this could be |
||
1248 | * $elemMatch criteria for matching a DBRef. |
||
1249 | * |
||
1250 | * @param mixed $value |
||
1251 | * @return boolean |
||
1252 | */ |
||
1253 | 70 | private function hasDBRefFields($value) |
|
1271 | |||
1272 | /** |
||
1273 | * Checks whether the value has query operators. |
||
1274 | * |
||
1275 | * @param mixed $value |
||
1276 | * @return boolean |
||
1277 | */ |
||
1278 | 74 | private function hasQueryOperators($value) |
|
1296 | |||
1297 | /** |
||
1298 | * Gets the array of discriminator values for the given ClassMetadata |
||
1299 | * |
||
1300 | * @param ClassMetadata $metadata |
||
1301 | * @return array |
||
1302 | */ |
||
1303 | 29 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1319 | |||
1320 | 606 | private function handleCollections($document, $options) |
|
1339 | |||
1340 | /** |
||
1341 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
1342 | * Also, shard key field should be present in actual document data. |
||
1343 | * |
||
1344 | * @param object $document |
||
1345 | * @param string $shardKeyField |
||
1346 | * @param array $actualDocumentData |
||
1347 | * |
||
1348 | * @throws MongoDBException |
||
1349 | */ |
||
1350 | 9 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
1366 | |||
1367 | /** |
||
1368 | * Get shard key aware query for single document. |
||
1369 | * |
||
1370 | * @param object $document |
||
1371 | * |
||
1372 | * @return array |
||
1373 | */ |
||
1374 | 299 | private function getQueryForDocument($document) |
|
1384 | |||
1385 | /** |
||
1386 | * @param array $options |
||
1387 | * |
||
1388 | * @return array |
||
1389 | */ |
||
1390 | 607 | private function getWriteOptions(array $options = array()) |
|
1400 | |||
1401 | /** |
||
1402 | * @param string $fieldName |
||
1403 | * @param mixed $value |
||
1404 | * @param array $mapping |
||
1405 | * @param bool $inNewObj |
||
1406 | * @return array |
||
1407 | */ |
||
1408 | 13 | private function prepareDbRefElement($fieldName, $value, array $mapping, $inNewObj) |
|
1435 | } |
||
1436 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: