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 |
||
52 | class DocumentPersister |
||
53 | { |
||
54 | /** |
||
55 | * The PersistenceBuilder instance. |
||
56 | * |
||
57 | * @var PersistenceBuilder |
||
58 | */ |
||
59 | private $pb; |
||
60 | |||
61 | /** |
||
62 | * The DocumentManager instance. |
||
63 | * |
||
64 | * @var DocumentManager |
||
65 | */ |
||
66 | private $dm; |
||
67 | |||
68 | /** |
||
69 | * The EventManager instance |
||
70 | * |
||
71 | * @var EventManager |
||
72 | */ |
||
73 | private $evm; |
||
74 | |||
75 | /** |
||
76 | * The UnitOfWork instance. |
||
77 | * |
||
78 | * @var UnitOfWork |
||
79 | */ |
||
80 | private $uow; |
||
81 | |||
82 | /** |
||
83 | * The ClassMetadata instance for the document type being persisted. |
||
84 | * |
||
85 | * @var ClassMetadata |
||
86 | */ |
||
87 | private $class; |
||
88 | |||
89 | /** |
||
90 | * The MongoCollection instance for this document. |
||
91 | * |
||
92 | * @var Collection |
||
93 | */ |
||
94 | private $collection; |
||
95 | |||
96 | /** |
||
97 | * Array of queued inserts for the persister to insert. |
||
98 | * |
||
99 | * @var array |
||
100 | */ |
||
101 | private $queuedInserts = array(); |
||
102 | |||
103 | /** |
||
104 | * Array of queued inserts for the persister to insert. |
||
105 | * |
||
106 | * @var array |
||
107 | */ |
||
108 | private $queuedUpserts = array(); |
||
109 | |||
110 | /** |
||
111 | * The CriteriaMerger instance. |
||
112 | * |
||
113 | * @var CriteriaMerger |
||
114 | */ |
||
115 | private $cm; |
||
116 | |||
117 | /** |
||
118 | * The CollectionPersister instance. |
||
119 | * |
||
120 | * @var CollectionPersister |
||
121 | */ |
||
122 | private $cp; |
||
123 | |||
124 | /** |
||
125 | * Initializes this instance. |
||
126 | * |
||
127 | * @param PersistenceBuilder $pb |
||
128 | * @param DocumentManager $dm |
||
129 | * @param EventManager $evm |
||
130 | * @param UnitOfWork $uow |
||
131 | * @param HydratorFactory $hydratorFactory |
||
132 | * @param ClassMetadata $class |
||
133 | * @param CriteriaMerger $cm |
||
134 | */ |
||
135 | 1084 | public function __construct( |
|
136 | PersistenceBuilder $pb, |
||
137 | DocumentManager $dm, |
||
138 | EventManager $evm, |
||
139 | UnitOfWork $uow, |
||
140 | HydratorFactory $hydratorFactory, |
||
141 | ClassMetadata $class, |
||
142 | CriteriaMerger $cm = null |
||
143 | ) { |
||
144 | 1084 | $this->pb = $pb; |
|
145 | 1084 | $this->dm = $dm; |
|
146 | 1084 | $this->evm = $evm; |
|
147 | 1084 | $this->cm = $cm ?: new CriteriaMerger(); |
|
148 | 1084 | $this->uow = $uow; |
|
149 | 1084 | $this->hydratorFactory = $hydratorFactory; |
|
|
|||
150 | 1084 | $this->class = $class; |
|
151 | 1084 | $this->collection = $dm->getDocumentCollection($class->name); |
|
152 | 1084 | $this->cp = $this->uow->getCollectionPersister(); |
|
153 | 1084 | } |
|
154 | |||
155 | /** |
||
156 | * @return array |
||
157 | */ |
||
158 | public function getInserts() |
||
159 | { |
||
160 | return $this->queuedInserts; |
||
161 | } |
||
162 | |||
163 | /** |
||
164 | * @param object $document |
||
165 | * @return bool |
||
166 | */ |
||
167 | public function isQueuedForInsert($document) |
||
168 | { |
||
169 | return isset($this->queuedInserts[spl_object_hash($document)]); |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * Adds a document to the queued insertions. |
||
174 | * The document remains queued until {@link executeInserts} is invoked. |
||
175 | * |
||
176 | * @param object $document The document to queue for insertion. |
||
177 | */ |
||
178 | 485 | public function addInsert($document) |
|
179 | { |
||
180 | 485 | $this->queuedInserts[spl_object_hash($document)] = $document; |
|
181 | 485 | } |
|
182 | |||
183 | /** |
||
184 | * @return array |
||
185 | */ |
||
186 | public function getUpserts() |
||
187 | { |
||
188 | return $this->queuedUpserts; |
||
189 | } |
||
190 | |||
191 | /** |
||
192 | * @param object $document |
||
193 | * @return boolean |
||
194 | */ |
||
195 | public function isQueuedForUpsert($document) |
||
196 | { |
||
197 | return isset($this->queuedUpserts[spl_object_hash($document)]); |
||
198 | } |
||
199 | |||
200 | /** |
||
201 | * Adds a document to the queued upserts. |
||
202 | * The document remains queued until {@link executeUpserts} is invoked. |
||
203 | * |
||
204 | * @param object $document The document to queue for insertion. |
||
205 | */ |
||
206 | 85 | public function addUpsert($document) |
|
207 | { |
||
208 | 85 | $this->queuedUpserts[spl_object_hash($document)] = $document; |
|
209 | 85 | } |
|
210 | |||
211 | /** |
||
212 | * Gets the ClassMetadata instance of the document class this persister is used for. |
||
213 | * |
||
214 | * @return ClassMetadata |
||
215 | */ |
||
216 | public function getClassMetadata() |
||
217 | { |
||
218 | return $this->class; |
||
219 | } |
||
220 | |||
221 | /** |
||
222 | * Executes all queued document insertions. |
||
223 | * |
||
224 | * Queued documents without an ID will inserted in a batch and queued |
||
225 | * documents with an ID will be upserted individually. |
||
226 | * |
||
227 | * If no inserts are queued, invoking this method is a NOOP. |
||
228 | * |
||
229 | * @param array $options Options for batchInsert() and update() driver methods |
||
230 | */ |
||
231 | 485 | public function executeInserts(array $options = array()) |
|
232 | { |
||
233 | 485 | if ( ! $this->queuedInserts) { |
|
234 | return; |
||
235 | } |
||
236 | |||
237 | 485 | $inserts = array(); |
|
238 | 485 | $options = $this->getWriteOptions($options); |
|
239 | 485 | foreach ($this->queuedInserts as $oid => $document) { |
|
240 | 485 | $data = $this->pb->prepareInsertData($document); |
|
241 | |||
242 | // Set the initial version for each insert |
||
243 | 484 | View Code Duplication | if ($this->class->isVersioned) { |
244 | 20 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
245 | 20 | if ($versionMapping['type'] === 'int') { |
|
246 | 18 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
247 | 18 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
248 | 2 | } elseif ($versionMapping['type'] === 'date') { |
|
249 | 2 | $nextVersionDateTime = new \DateTime(); |
|
250 | 2 | $nextVersion = Type::convertPHPToDatabaseValue($nextVersionDateTime); |
|
251 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
252 | } |
||
253 | 20 | $data[$versionMapping['name']] = $nextVersion; |
|
254 | } |
||
255 | |||
256 | 484 | $inserts[] = $data; |
|
257 | } |
||
258 | |||
259 | 484 | if ($inserts) { |
|
260 | try { |
||
261 | 484 | $this->collection->insertMany($inserts, $options); |
|
262 | 6 | } catch (DriverException $e) { |
|
263 | 6 | $this->queuedInserts = array(); |
|
264 | 6 | throw $e; |
|
265 | } |
||
266 | } |
||
267 | |||
268 | /* All collections except for ones using addToSet have already been |
||
269 | * saved. We have left these to be handled separately to avoid checking |
||
270 | * collection for uniqueness on PHP side. |
||
271 | */ |
||
272 | 484 | foreach ($this->queuedInserts as $document) { |
|
273 | 484 | $this->handleCollections($document, $options); |
|
274 | } |
||
275 | |||
276 | 484 | $this->queuedInserts = array(); |
|
277 | 484 | } |
|
278 | |||
279 | /** |
||
280 | * Executes all queued document upserts. |
||
281 | * |
||
282 | * Queued documents with an ID are upserted individually. |
||
283 | * |
||
284 | * If no upserts are queued, invoking this method is a NOOP. |
||
285 | * |
||
286 | * @param array $options Options for batchInsert() and update() driver methods |
||
287 | */ |
||
288 | 85 | public function executeUpserts(array $options = array()) |
|
289 | { |
||
290 | 85 | if ( ! $this->queuedUpserts) { |
|
291 | return; |
||
292 | } |
||
293 | |||
294 | 85 | $options = $this->getWriteOptions($options); |
|
295 | 85 | foreach ($this->queuedUpserts as $oid => $document) { |
|
296 | try { |
||
297 | 85 | $this->executeUpsert($document, $options); |
|
298 | 85 | $this->handleCollections($document, $options); |
|
299 | 85 | unset($this->queuedUpserts[$oid]); |
|
300 | } catch (\MongoException $e) { |
||
301 | unset($this->queuedUpserts[$oid]); |
||
302 | 85 | throw $e; |
|
303 | } |
||
304 | } |
||
305 | 85 | } |
|
306 | |||
307 | /** |
||
308 | * Executes a single upsert in {@link executeUpserts} |
||
309 | * |
||
310 | * @param object $document |
||
311 | * @param array $options |
||
312 | */ |
||
313 | 85 | private function executeUpsert($document, array $options) |
|
314 | { |
||
315 | 85 | $options['upsert'] = true; |
|
316 | 85 | $criteria = $this->getQueryForDocument($document); |
|
317 | |||
318 | 85 | $data = $this->pb->prepareUpsertData($document); |
|
319 | |||
320 | // Set the initial version for each upsert |
||
321 | 85 | View Code Duplication | if ($this->class->isVersioned) { |
322 | 2 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
323 | 2 | if ($versionMapping['type'] === 'int') { |
|
324 | 1 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
325 | 1 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
326 | 1 | } elseif ($versionMapping['type'] === 'date') { |
|
327 | 1 | $nextVersionDateTime = new \DateTime(); |
|
328 | 1 | $nextVersion = Type::convertPHPToDatabaseValue($nextVersionDateTime); |
|
329 | 1 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
330 | } |
||
331 | 2 | $data['$set'][$versionMapping['name']] = $nextVersion; |
|
332 | } |
||
333 | |||
334 | 85 | foreach (array_keys($criteria) as $field) { |
|
335 | 85 | unset($data['$set'][$field]); |
|
336 | } |
||
337 | |||
338 | // Do not send an empty $set modifier |
||
339 | 85 | if (empty($data['$set'])) { |
|
340 | 17 | unset($data['$set']); |
|
341 | } |
||
342 | |||
343 | /* If there are no modifiers remaining, we're upserting a document with |
||
344 | * an identifier as its only field. Since a document with the identifier |
||
345 | * may already exist, the desired behavior is "insert if not exists" and |
||
346 | * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set |
||
347 | * the identifier to the same value in our criteria. |
||
348 | * |
||
349 | * This will fail for versions before MongoDB 2.6, which require an |
||
350 | * empty $set modifier. The best we can do (without attempting to check |
||
351 | * server versions in advance) is attempt the 2.6+ behavior and retry |
||
352 | * after the relevant exception. |
||
353 | * |
||
354 | * See: https://jira.mongodb.org/browse/SERVER-12266 |
||
355 | */ |
||
356 | 85 | if (empty($data)) { |
|
357 | 17 | $retry = true; |
|
358 | 17 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
359 | } |
||
360 | |||
361 | try { |
||
362 | 85 | $this->collection->updateOne($criteria, $data, $options); |
|
363 | 85 | return; |
|
364 | } catch (\MongoCursorException $e) { |
||
365 | if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) { |
||
366 | throw $e; |
||
367 | } |
||
368 | } |
||
369 | |||
370 | $this->collection->updateOne($criteria, array('$set' => new \stdClass), $options); |
||
371 | } |
||
372 | |||
373 | /** |
||
374 | * Updates the already persisted document if it has any new changesets. |
||
375 | * |
||
376 | * @param object $document |
||
377 | * @param array $options Array of options to be used with update() |
||
378 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
379 | */ |
||
380 | 199 | public function update($document, array $options = array()) |
|
381 | { |
||
382 | 199 | $update = $this->pb->prepareUpdateData($document); |
|
383 | |||
384 | 199 | $query = $this->getQueryForDocument($document); |
|
385 | |||
386 | 199 | foreach (array_keys($query) as $field) { |
|
387 | 199 | unset($update['$set'][$field]); |
|
388 | } |
||
389 | |||
390 | 199 | if (empty($update['$set'])) { |
|
391 | 89 | unset($update['$set']); |
|
392 | } |
||
393 | |||
394 | |||
395 | // Include versioning logic to set the new version value in the database |
||
396 | // and to ensure the version has not changed since this document object instance |
||
397 | // was fetched from the database |
||
398 | 199 | $nextVersion = null; |
|
399 | 199 | if ($this->class->isVersioned) { |
|
400 | 13 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
401 | 13 | $currentVersion = $this->class->reflFields[$this->class->versionField]->getValue($document); |
|
402 | 13 | if ($versionMapping['type'] === 'int') { |
|
403 | 10 | $nextVersion = $currentVersion + 1; |
|
404 | 10 | $update['$inc'][$versionMapping['name']] = 1; |
|
405 | 10 | $query[$versionMapping['name']] = $currentVersion; |
|
406 | 3 | } elseif ($versionMapping['type'] === 'date') { |
|
407 | 3 | $nextVersion = new \DateTime(); |
|
408 | 3 | $update['$set'][$versionMapping['name']] = Type::convertPHPToDatabaseValue($nextVersion); |
|
409 | 3 | $query[$versionMapping['name']] = Type::convertPHPToDatabaseValue($currentVersion); |
|
410 | } |
||
411 | } |
||
412 | |||
413 | 199 | if ( ! empty($update)) { |
|
414 | // Include locking logic so that if the document object in memory is currently |
||
415 | // locked then it will remove it, otherwise it ensures the document is not locked. |
||
416 | 133 | if ($this->class->isLockable) { |
|
417 | 11 | $isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document); |
|
418 | 11 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
419 | 11 | if ($isLocked) { |
|
420 | 2 | $update['$unset'] = array($lockMapping['name'] => true); |
|
421 | } else { |
||
422 | 9 | $query[$lockMapping['name']] = array('$exists' => false); |
|
423 | } |
||
424 | } |
||
425 | |||
426 | 133 | $options = $this->getWriteOptions($options); |
|
427 | |||
428 | 133 | $result = $this->collection->updateOne($query, $update, $options); |
|
429 | |||
430 | 133 | if (($this->class->isVersioned || $this->class->isLockable) && $result->getModifiedCount() !== 1) { |
|
431 | 4 | throw LockException::lockFailed($document); |
|
432 | 129 | } elseif ($this->class->isVersioned) { |
|
433 | 9 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
434 | } |
||
435 | } |
||
436 | |||
437 | 195 | $this->handleCollections($document, $options); |
|
438 | 195 | } |
|
439 | |||
440 | /** |
||
441 | * Removes document from mongo |
||
442 | * |
||
443 | * @param mixed $document |
||
444 | * @param array $options Array of options to be used with remove() |
||
445 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
446 | */ |
||
447 | 33 | public function delete($document, array $options = array()) |
|
448 | { |
||
449 | 33 | $query = $this->getQueryForDocument($document); |
|
450 | |||
451 | 33 | if ($this->class->isLockable) { |
|
452 | 2 | $query[$this->class->lockField] = array('$exists' => false); |
|
453 | } |
||
454 | |||
455 | 33 | $options = $this->getWriteOptions($options); |
|
456 | |||
457 | 33 | $result = $this->collection->deleteOne($query, $options); |
|
458 | |||
459 | 33 | if (($this->class->isVersioned || $this->class->isLockable) && ! $result->getDeletedCount()) { |
|
460 | 2 | throw LockException::lockFailed($document); |
|
461 | } |
||
462 | 31 | } |
|
463 | |||
464 | /** |
||
465 | * Refreshes a managed document. |
||
466 | * |
||
467 | * @param object $document The document to refresh. |
||
468 | */ |
||
469 | 20 | public function refresh($document) |
|
470 | { |
||
471 | 20 | $query = $this->getQueryForDocument($document); |
|
472 | 20 | $data = $this->collection->findOne($query); |
|
473 | 20 | $data = $this->hydratorFactory->hydrate($document, $data); |
|
474 | 20 | $this->uow->setOriginalDocumentData($document, $data); |
|
475 | 20 | } |
|
476 | |||
477 | /** |
||
478 | * Finds a document by a set of criteria. |
||
479 | * |
||
480 | * If a scalar or MongoDB\BSON\ObjectId is provided for $criteria, it will |
||
481 | * be used to match an _id value. |
||
482 | * |
||
483 | * @param mixed $criteria Query criteria |
||
484 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
485 | * @param array $hints Hints for document creation |
||
486 | * @param integer $lockMode |
||
487 | * @param array $sort Sort array for Cursor::sort() |
||
488 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
489 | * @return object|null The loaded and managed document instance or null if no document was found |
||
490 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
491 | */ |
||
492 | 348 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
493 | { |
||
494 | // TODO: remove this |
||
495 | 348 | if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoDB\BSON\ObjectId) { |
|
496 | $criteria = array('_id' => $criteria); |
||
497 | } |
||
498 | |||
499 | 348 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
500 | 348 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
501 | 348 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
502 | |||
503 | 348 | $options = []; |
|
504 | 348 | if (null !== $sort) { |
|
505 | 92 | $options['sort'] = $this->prepareSort($sort); |
|
506 | } |
||
507 | 348 | $result = $this->collection->findOne($criteria, $options); |
|
508 | |||
509 | 348 | if ($this->class->isLockable) { |
|
510 | 1 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
511 | 1 | if (isset($result[$lockMapping['name']]) && $result[$lockMapping['name']] === LockMode::PESSIMISTIC_WRITE) { |
|
512 | 1 | throw LockException::lockFailed($result); |
|
513 | } |
||
514 | } |
||
515 | |||
516 | 347 | return $this->createDocument($result, $document, $hints); |
|
517 | } |
||
518 | |||
519 | /** |
||
520 | * Finds documents by a set of criteria. |
||
521 | * |
||
522 | * @param array $criteria Query criteria |
||
523 | * @param array $sort Sort array for Cursor::sort() |
||
524 | * @param integer|null $limit Limit for Cursor::limit() |
||
525 | * @param integer|null $skip Skip for Cursor::skip() |
||
526 | * @return Iterator |
||
527 | */ |
||
528 | 22 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
529 | { |
||
530 | 22 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
531 | 22 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
532 | 22 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
533 | |||
534 | 22 | $options = []; |
|
535 | 22 | if (null !== $sort) { |
|
536 | 11 | $options['sort'] = $this->prepareSort($sort); |
|
537 | } |
||
538 | |||
539 | 22 | if (null !== $limit) { |
|
540 | 10 | $options['limit'] = $limit; |
|
541 | } |
||
542 | |||
543 | 22 | if (null !== $skip) { |
|
544 | 1 | $options['skip'] = $skip; |
|
545 | } |
||
546 | |||
547 | 22 | $baseCursor = $this->collection->find($criteria, $options); |
|
548 | 22 | $cursor = $this->wrapCursor($baseCursor); |
|
549 | |||
550 | 22 | return $cursor; |
|
551 | } |
||
552 | |||
553 | /** |
||
554 | * @param object $document |
||
555 | * |
||
556 | * @return array |
||
557 | * @throws MongoDBException |
||
558 | */ |
||
559 | 274 | private function getShardKeyQuery($document) |
|
592 | |||
593 | /** |
||
594 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
595 | * |
||
596 | * @param Cursor $baseCursor |
||
597 | * @return Iterator |
||
598 | */ |
||
599 | 22 | private function wrapCursor(Cursor $baseCursor): Iterator |
|
603 | |||
604 | /** |
||
605 | * Checks whether the given managed document exists in the database. |
||
606 | * |
||
607 | * @param object $document |
||
608 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
609 | */ |
||
610 | 3 | public function exists($document) |
|
615 | |||
616 | /** |
||
617 | * Locks document by storing the lock mode on the mapped lock field. |
||
618 | * |
||
619 | * @param object $document |
||
620 | * @param int $lockMode |
||
621 | */ |
||
622 | 5 | public function lock($document, $lockMode) |
|
630 | |||
631 | /** |
||
632 | * Releases any lock that exists on this document. |
||
633 | * |
||
634 | * @param object $document |
||
635 | */ |
||
636 | 1 | public function unlock($document) |
|
644 | |||
645 | /** |
||
646 | * Creates or fills a single document object from an query result. |
||
647 | * |
||
648 | * @param object $result The query result. |
||
649 | * @param object $document The document object to fill, if any. |
||
650 | * @param array $hints Hints for document creation. |
||
651 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
652 | */ |
||
653 | 347 | private function createDocument($result, $document = null, array $hints = array()) |
|
667 | |||
668 | /** |
||
669 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
670 | * |
||
671 | * @param PersistentCollectionInterface $collection |
||
672 | */ |
||
673 | 163 | public function loadCollection(PersistentCollectionInterface $collection) |
|
674 | { |
||
675 | 163 | $mapping = $collection->getMapping(); |
|
676 | 163 | switch ($mapping['association']) { |
|
677 | 163 | case ClassMetadata::EMBED_MANY: |
|
678 | 109 | $this->loadEmbedManyCollection($collection); |
|
679 | 109 | break; |
|
680 | |||
681 | 76 | case ClassMetadata::REFERENCE_MANY: |
|
682 | 76 | if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) { |
|
683 | 5 | $this->loadReferenceManyWithRepositoryMethod($collection); |
|
684 | } else { |
||
685 | 72 | if ($mapping['isOwningSide']) { |
|
686 | 60 | $this->loadReferenceManyCollectionOwningSide($collection); |
|
687 | } else { |
||
688 | 17 | $this->loadReferenceManyCollectionInverseSide($collection); |
|
689 | } |
||
690 | } |
||
691 | 76 | break; |
|
692 | } |
||
693 | 163 | } |
|
694 | |||
695 | 109 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
724 | |||
725 | 60 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
726 | { |
||
727 | 60 | $hints = $collection->getHints(); |
|
728 | 60 | $mapping = $collection->getMapping(); |
|
729 | 60 | $groupedIds = array(); |
|
730 | |||
731 | 60 | $sorted = isset($mapping['sort']) && $mapping['sort']; |
|
732 | |||
733 | 60 | foreach ($collection->getMongoData() as $key => $reference) { |
|
734 | 54 | $className = $this->uow->getClassNameForAssociation($mapping, $reference); |
|
735 | 54 | $identifier = ClassMetadataInfo::getReferenceId($reference, $mapping['storeAs']); |
|
736 | 54 | $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($identifier); |
|
737 | |||
738 | // create a reference to the class and id |
||
739 | 54 | $reference = $this->dm->getReference($className, $id); |
|
740 | |||
741 | // no custom sort so add the references right now in the order they are embedded |
||
742 | 54 | if ( ! $sorted) { |
|
743 | 53 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
744 | 2 | $collection->set($key, $reference); |
|
745 | } else { |
||
746 | 51 | $collection->add($reference); |
|
747 | } |
||
748 | } |
||
749 | |||
750 | // only query for the referenced object if it is not already initialized or the collection is sorted |
||
751 | 54 | if (($reference instanceof Proxy && ! $reference->__isInitialized__) || $sorted) { |
|
752 | 54 | $groupedIds[$className][] = $identifier; |
|
753 | } |
||
754 | } |
||
755 | 60 | foreach ($groupedIds as $className => $ids) { |
|
756 | 39 | $class = $this->dm->getClassMetadata($className); |
|
757 | 39 | $mongoCollection = $this->dm->getDocumentCollection($className); |
|
758 | 39 | $criteria = $this->cm->merge( |
|
759 | 39 | array('_id' => array('$in' => array_values($ids))), |
|
760 | 39 | $this->dm->getFilterCollection()->getFilterCriteria($class), |
|
761 | 39 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
762 | ); |
||
763 | 39 | $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); |
|
764 | |||
765 | 39 | $options = []; |
|
766 | 39 | if (isset($mapping['sort'])) { |
|
767 | 39 | $options['sort'] = $this->prepareSort($mapping['sort']); |
|
768 | } |
||
769 | 39 | if (isset($mapping['limit'])) { |
|
770 | $options['limit'] = $mapping['limit']; |
||
771 | } |
||
772 | 39 | if (isset($mapping['skip'])) { |
|
773 | $options['skip'] = $mapping['skip']; |
||
774 | } |
||
775 | 39 | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
|
776 | $options['readPreference'] = $hints[Query::HINT_READ_PREFERENCE]; |
||
777 | } |
||
778 | |||
779 | 39 | $cursor = $mongoCollection->find($criteria, $options); |
|
780 | 39 | $documents = $cursor->toArray(); |
|
781 | 39 | foreach ($documents as $documentData) { |
|
782 | 38 | $document = $this->uow->getById($documentData['_id'], $class); |
|
783 | 38 | if ($document instanceof Proxy && ! $document->__isInitialized()) { |
|
784 | 38 | $data = $this->hydratorFactory->hydrate($document, $documentData); |
|
785 | 38 | $this->uow->setOriginalDocumentData($document, $data); |
|
786 | 38 | $document->__isInitialized__ = true; |
|
787 | } |
||
788 | 38 | if ($sorted) { |
|
789 | 39 | $collection->add($document); |
|
790 | } |
||
791 | } |
||
792 | } |
||
793 | 60 | } |
|
794 | |||
795 | 17 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
803 | |||
804 | /** |
||
805 | * @param PersistentCollectionInterface $collection |
||
806 | * |
||
807 | * @return Query |
||
808 | */ |
||
809 | 17 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
810 | { |
||
811 | 17 | $hints = $collection->getHints(); |
|
812 | 17 | $mapping = $collection->getMapping(); |
|
813 | 17 | $owner = $collection->getOwner(); |
|
814 | 17 | $ownerClass = $this->dm->getClassMetadata(get_class($owner)); |
|
815 | 17 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
816 | 17 | $mappedByMapping = isset($targetClass->fieldMappings[$mapping['mappedBy']]) ? $targetClass->fieldMappings[$mapping['mappedBy']] : array(); |
|
817 | 17 | $mappedByFieldName = ClassMetadataInfo::getReferenceFieldName(isset($mappedByMapping['storeAs']) ? $mappedByMapping['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF, $mapping['mappedBy']); |
|
818 | |||
819 | 17 | $criteria = $this->cm->merge( |
|
820 | 17 | array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), |
|
821 | 17 | $this->dm->getFilterCollection()->getFilterCriteria($targetClass), |
|
848 | |||
849 | 5 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
862 | |||
863 | /** |
||
864 | * @param PersistentCollectionInterface $collection |
||
865 | * |
||
866 | * @return \Iterator |
||
867 | */ |
||
868 | 5 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
889 | |||
890 | /** |
||
891 | * Prepare a projection array by converting keys, which are PHP property |
||
892 | * names, to MongoDB field names. |
||
893 | * |
||
894 | * @param array $fields |
||
895 | * @return array |
||
896 | */ |
||
897 | 14 | public function prepareProjection(array $fields) |
|
907 | |||
908 | /** |
||
909 | * @param $sort |
||
910 | * @return int |
||
911 | */ |
||
912 | 25 | private function getSortDirection($sort) |
|
924 | |||
925 | /** |
||
926 | * Prepare a sort specification array by converting keys to MongoDB field |
||
927 | * names and changing direction strings to int. |
||
928 | * |
||
929 | * @param array $fields |
||
930 | * @return array |
||
931 | */ |
||
932 | 141 | public function prepareSort(array $fields) |
|
942 | |||
943 | /** |
||
944 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
945 | * |
||
946 | * @param string $fieldName |
||
947 | * @return string |
||
948 | */ |
||
949 | 433 | public function prepareFieldName($fieldName) |
|
955 | |||
956 | /** |
||
957 | * Adds discriminator criteria to an already-prepared query. |
||
958 | * |
||
959 | * This method should be used once for query criteria and not be used for |
||
960 | * nested expressions. It should be called before |
||
961 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
962 | * |
||
963 | * @param array $preparedQuery |
||
964 | * @return array |
||
965 | */ |
||
966 | 498 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
982 | |||
983 | /** |
||
984 | * Adds filter criteria to an already-prepared query. |
||
985 | * |
||
986 | * This method should be used once for query criteria and not be used for |
||
987 | * nested expressions. It should be called after |
||
988 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
989 | * |
||
990 | * @param array $preparedQuery |
||
991 | * @return array |
||
992 | */ |
||
993 | 499 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
1007 | |||
1008 | /** |
||
1009 | * Prepares the query criteria or new document object. |
||
1010 | * |
||
1011 | * PHP field names and types will be converted to those used by MongoDB. |
||
1012 | * |
||
1013 | * @param array $query |
||
1014 | * @param bool $isNewObj |
||
1015 | * @return array |
||
1016 | */ |
||
1017 | 531 | public function prepareQueryOrNewObj(array $query, $isNewObj = false) |
|
1045 | |||
1046 | /** |
||
1047 | * Prepares a query value and converts the PHP value to the database value |
||
1048 | * if it is an identifier. |
||
1049 | * |
||
1050 | * It also handles converting $fieldName to the database name if they are different. |
||
1051 | * |
||
1052 | * @param string $fieldName |
||
1053 | * @param mixed $value |
||
1054 | * @param ClassMetadata $class Defaults to $this->class |
||
1055 | * @param bool $prepareValue Whether or not to prepare the value |
||
1056 | * @param bool $inNewObj Whether or not newObj is being prepared |
||
1057 | * @return array An array of tuples containing prepared field names and values |
||
1058 | */ |
||
1059 | 882 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true, $inNewObj = false) |
|
1246 | |||
1247 | /** |
||
1248 | * Prepares a query expression. |
||
1249 | * |
||
1250 | * @param array|object $expression |
||
1251 | * @param ClassMetadata $class |
||
1252 | * @return array |
||
1253 | */ |
||
1254 | 78 | private function prepareQueryExpression($expression, $class) |
|
1281 | |||
1282 | /** |
||
1283 | * Checks whether the value has DBRef fields. |
||
1284 | * |
||
1285 | * This method doesn't check if the the value is a complete DBRef object, |
||
1286 | * although it should return true for a DBRef. Rather, we're checking that |
||
1287 | * the value has one or more fields for a DBref. In practice, this could be |
||
1288 | * $elemMatch criteria for matching a DBRef. |
||
1289 | * |
||
1290 | * @param mixed $value |
||
1291 | * @return boolean |
||
1292 | */ |
||
1293 | 79 | private function hasDBRefFields($value) |
|
1311 | |||
1312 | /** |
||
1313 | * Checks whether the value has query operators. |
||
1314 | * |
||
1315 | * @param mixed $value |
||
1316 | * @return boolean |
||
1317 | */ |
||
1318 | 83 | private function hasQueryOperators($value) |
|
1336 | |||
1337 | /** |
||
1338 | * Gets the array of discriminator values for the given ClassMetadata |
||
1339 | * |
||
1340 | * @param ClassMetadata $metadata |
||
1341 | * @return array |
||
1342 | */ |
||
1343 | 29 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1359 | |||
1360 | 557 | private function handleCollections($document, $options) |
|
1379 | |||
1380 | /** |
||
1381 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
1382 | * Also, shard key field should be present in actual document data. |
||
1383 | * |
||
1384 | * @param object $document |
||
1385 | * @param string $shardKeyField |
||
1386 | * @param array $actualDocumentData |
||
1387 | * |
||
1388 | * @throws MongoDBException |
||
1389 | */ |
||
1390 | 4 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
1406 | |||
1407 | /** |
||
1408 | * Get shard key aware query for single document. |
||
1409 | * |
||
1410 | * @param object $document |
||
1411 | * |
||
1412 | * @return array |
||
1413 | */ |
||
1414 | 270 | private function getQueryForDocument($document) |
|
1424 | |||
1425 | /** |
||
1426 | * @param array $options |
||
1427 | * |
||
1428 | * @return array |
||
1429 | */ |
||
1430 | 558 | private function getWriteOptions(array $options = array()) |
|
1440 | |||
1441 | /** |
||
1442 | * @param string $fieldName |
||
1443 | * @param mixed $value |
||
1444 | * @param array $mapping |
||
1445 | * @param bool $inNewObj |
||
1446 | * @return array |
||
1447 | */ |
||
1448 | 15 | private function prepareReference($fieldName, $value, array $mapping, $inNewObj) |
|
1488 | } |
||
1489 |
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: