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 |
||
48 | class DocumentPersister |
||
49 | { |
||
50 | /** |
||
51 | * The PersistenceBuilder instance. |
||
52 | * |
||
53 | * @var PersistenceBuilder |
||
54 | */ |
||
55 | private $pb; |
||
56 | |||
57 | /** |
||
58 | * The DocumentManager instance. |
||
59 | * |
||
60 | * @var DocumentManager |
||
61 | */ |
||
62 | private $dm; |
||
63 | |||
64 | /** |
||
65 | * The EventManager instance |
||
66 | * |
||
67 | * @var EventManager |
||
68 | */ |
||
69 | private $evm; |
||
70 | |||
71 | /** |
||
72 | * The UnitOfWork instance. |
||
73 | * |
||
74 | * @var UnitOfWork |
||
75 | */ |
||
76 | private $uow; |
||
77 | |||
78 | /** |
||
79 | * The ClassMetadata instance for the document type being persisted. |
||
80 | * |
||
81 | * @var ClassMetadata |
||
82 | */ |
||
83 | private $class; |
||
84 | |||
85 | /** |
||
86 | * The MongoCollection instance for this document. |
||
87 | * |
||
88 | * @var \MongoCollection |
||
89 | */ |
||
90 | private $collection; |
||
91 | |||
92 | /** |
||
93 | * Array of queued inserts for the persister to insert. |
||
94 | * |
||
95 | * @var array |
||
96 | */ |
||
97 | private $queuedInserts = array(); |
||
98 | |||
99 | /** |
||
100 | * Array of queued inserts for the persister to insert. |
||
101 | * |
||
102 | * @var array |
||
103 | */ |
||
104 | private $queuedUpserts = array(); |
||
105 | |||
106 | /** |
||
107 | * The CriteriaMerger instance. |
||
108 | * |
||
109 | * @var CriteriaMerger |
||
110 | */ |
||
111 | private $cm; |
||
112 | |||
113 | /** |
||
114 | * The CollectionPersister instance. |
||
115 | * |
||
116 | * @var CollectionPersister |
||
117 | */ |
||
118 | private $cp; |
||
119 | |||
120 | /** |
||
121 | * Initializes this instance. |
||
122 | * |
||
123 | * @param PersistenceBuilder $pb |
||
124 | * @param DocumentManager $dm |
||
125 | * @param EventManager $evm |
||
126 | * @param UnitOfWork $uow |
||
127 | * @param HydratorFactory $hydratorFactory |
||
128 | * @param ClassMetadata $class |
||
129 | * @param CriteriaMerger $cm |
||
130 | */ |
||
131 | 793 | public function __construct( |
|
132 | PersistenceBuilder $pb, |
||
133 | DocumentManager $dm, |
||
134 | EventManager $evm, |
||
135 | UnitOfWork $uow, |
||
136 | HydratorFactory $hydratorFactory, |
||
137 | ClassMetadata $class, |
||
138 | CriteriaMerger $cm = null |
||
139 | ) { |
||
140 | 793 | $this->pb = $pb; |
|
141 | 793 | $this->dm = $dm; |
|
142 | 793 | $this->evm = $evm; |
|
143 | 793 | $this->cm = $cm ?: new CriteriaMerger(); |
|
144 | 793 | $this->uow = $uow; |
|
145 | 793 | $this->hydratorFactory = $hydratorFactory; |
|
|
|||
146 | 793 | $this->class = $class; |
|
147 | 793 | $this->collection = $dm->getDocumentCollection($class->name); |
|
148 | 793 | $this->cp = $this->uow->getCollectionPersister(); |
|
149 | 793 | } |
|
150 | |||
151 | /** |
||
152 | * @return array |
||
153 | */ |
||
154 | public function getInserts() |
||
155 | { |
||
156 | return $this->queuedInserts; |
||
157 | } |
||
158 | |||
159 | /** |
||
160 | * @param object $document |
||
161 | * @return bool |
||
162 | */ |
||
163 | public function isQueuedForInsert($document) |
||
164 | { |
||
165 | return isset($this->queuedInserts[spl_object_hash($document)]); |
||
166 | } |
||
167 | |||
168 | /** |
||
169 | * Adds a document to the queued insertions. |
||
170 | * The document remains queued until {@link executeInserts} is invoked. |
||
171 | * |
||
172 | * @param object $document The document to queue for insertion. |
||
173 | */ |
||
174 | 551 | public function addInsert($document) |
|
175 | { |
||
176 | 551 | $this->queuedInserts[spl_object_hash($document)] = $document; |
|
177 | 551 | } |
|
178 | |||
179 | /** |
||
180 | * @return array |
||
181 | */ |
||
182 | public function getUpserts() |
||
183 | { |
||
184 | return $this->queuedUpserts; |
||
185 | } |
||
186 | |||
187 | /** |
||
188 | * @param object $document |
||
189 | * @return boolean |
||
190 | */ |
||
191 | public function isQueuedForUpsert($document) |
||
192 | { |
||
193 | return isset($this->queuedUpserts[spl_object_hash($document)]); |
||
194 | } |
||
195 | |||
196 | /** |
||
197 | * Adds a document to the queued upserts. |
||
198 | * The document remains queued until {@link executeUpserts} is invoked. |
||
199 | * |
||
200 | * @param object $document The document to queue for insertion. |
||
201 | */ |
||
202 | 88 | public function addUpsert($document) |
|
203 | { |
||
204 | 88 | $this->queuedUpserts[spl_object_hash($document)] = $document; |
|
205 | 88 | } |
|
206 | |||
207 | /** |
||
208 | * Gets the ClassMetadata instance of the document class this persister is used for. |
||
209 | * |
||
210 | * @return ClassMetadata |
||
211 | */ |
||
212 | public function getClassMetadata() |
||
213 | { |
||
214 | return $this->class; |
||
215 | } |
||
216 | |||
217 | /** |
||
218 | * Executes all queued document insertions. |
||
219 | * |
||
220 | * Queued documents without an ID will inserted in a batch and queued |
||
221 | * documents with an ID will be upserted individually. |
||
222 | * |
||
223 | * If no inserts are queued, invoking this method is a NOOP. |
||
224 | * |
||
225 | * @param array $options Options for batchInsert() and update() driver methods |
||
226 | */ |
||
227 | 551 | public function executeInserts(array $options = array()) |
|
228 | { |
||
229 | 551 | if ( ! $this->queuedInserts) { |
|
230 | return; |
||
231 | } |
||
232 | |||
233 | 551 | $inserts = array(); |
|
234 | 551 | $options = $this->getWriteOptions($options); |
|
235 | 551 | foreach ($this->queuedInserts as $oid => $document) { |
|
236 | 551 | $data = $this->pb->prepareInsertData($document); |
|
237 | |||
238 | // Set the initial version for each insert |
||
239 | 550 | View Code Duplication | if ($this->class->isVersioned) { |
240 | 39 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
241 | 39 | if ($versionMapping['type'] === 'int') { |
|
242 | 37 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
243 | 37 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
244 | 2 | } elseif ($versionMapping['type'] === 'date') { |
|
245 | 2 | $nextVersionDateTime = new \DateTime(); |
|
246 | 2 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
247 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
248 | } |
||
249 | 39 | $data[$versionMapping['name']] = $nextVersion; |
|
250 | } |
||
251 | |||
252 | 550 | $inserts[$oid] = $data; |
|
253 | } |
||
254 | |||
255 | 550 | if ($inserts) { |
|
256 | try { |
||
257 | 550 | $this->collection->batchInsert($inserts, $options); |
|
258 | 7 | } catch (\MongoException $e) { |
|
259 | 7 | $this->queuedInserts = array(); |
|
260 | 7 | throw $e; |
|
261 | } |
||
262 | } |
||
263 | |||
264 | /* All collections except for ones using addToSet have already been |
||
265 | * saved. We have left these to be handled separately to avoid checking |
||
266 | * collection for uniqueness on PHP side. |
||
267 | */ |
||
268 | 550 | foreach ($this->queuedInserts as $document) { |
|
269 | 550 | $this->handleCollections($document, $options); |
|
270 | } |
||
271 | |||
272 | 550 | $this->queuedInserts = array(); |
|
273 | 550 | } |
|
274 | |||
275 | /** |
||
276 | * Executes all queued document upserts. |
||
277 | * |
||
278 | * Queued documents with an ID are upserted individually. |
||
279 | * |
||
280 | * If no upserts are queued, invoking this method is a NOOP. |
||
281 | * |
||
282 | * @param array $options Options for batchInsert() and update() driver methods |
||
283 | */ |
||
284 | 88 | public function executeUpserts(array $options = array()) |
|
285 | { |
||
286 | 88 | if ( ! $this->queuedUpserts) { |
|
287 | return; |
||
288 | } |
||
289 | |||
290 | 88 | $options = $this->getWriteOptions($options); |
|
291 | 88 | foreach ($this->queuedUpserts as $oid => $document) { |
|
292 | try { |
||
293 | 88 | $this->executeUpsert($document, $options); |
|
294 | 88 | $this->handleCollections($document, $options); |
|
295 | 88 | unset($this->queuedUpserts[$oid]); |
|
296 | } catch (\MongoException $e) { |
||
297 | unset($this->queuedUpserts[$oid]); |
||
298 | 88 | throw $e; |
|
299 | } |
||
300 | } |
||
301 | 88 | } |
|
302 | |||
303 | /** |
||
304 | * Executes a single upsert in {@link executeUpserts} |
||
305 | * |
||
306 | * @param object $document |
||
307 | * @param array $options |
||
308 | */ |
||
309 | 88 | private function executeUpsert($document, array $options) |
|
310 | { |
||
311 | 88 | $options['upsert'] = true; |
|
312 | 88 | $criteria = $this->getQueryForDocument($document); |
|
313 | |||
314 | 88 | $data = $this->pb->prepareUpsertData($document); |
|
315 | |||
316 | // Set the initial version for each upsert |
||
317 | 88 | View Code Duplication | if ($this->class->isVersioned) { |
318 | 3 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
319 | 3 | if ($versionMapping['type'] === 'int') { |
|
320 | 2 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
321 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
322 | 1 | } elseif ($versionMapping['type'] === 'date') { |
|
323 | 1 | $nextVersionDateTime = new \DateTime(); |
|
324 | 1 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
325 | 1 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
326 | } |
||
327 | 3 | $data['$set'][$versionMapping['name']] = $nextVersion; |
|
328 | } |
||
329 | |||
330 | 88 | foreach (array_keys($criteria) as $field) { |
|
331 | 88 | unset($data['$set'][$field]); |
|
332 | } |
||
333 | |||
334 | // Do not send an empty $set modifier |
||
335 | 88 | if (empty($data['$set'])) { |
|
336 | 17 | unset($data['$set']); |
|
337 | } |
||
338 | |||
339 | /* If there are no modifiers remaining, we're upserting a document with |
||
340 | * an identifier as its only field. Since a document with the identifier |
||
341 | * may already exist, the desired behavior is "insert if not exists" and |
||
342 | * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set |
||
343 | * the identifier to the same value in our criteria. |
||
344 | * |
||
345 | * This will fail for versions before MongoDB 2.6, which require an |
||
346 | * empty $set modifier. The best we can do (without attempting to check |
||
347 | * server versions in advance) is attempt the 2.6+ behavior and retry |
||
348 | * after the relevant exception. |
||
349 | * |
||
350 | * See: https://jira.mongodb.org/browse/SERVER-12266 |
||
351 | */ |
||
352 | 88 | if (empty($data)) { |
|
353 | 17 | $retry = true; |
|
354 | 17 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
355 | } |
||
356 | |||
357 | try { |
||
358 | 88 | $this->collection->update($criteria, $data, $options); |
|
359 | 88 | return; |
|
360 | } catch (\MongoCursorException $e) { |
||
361 | if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) { |
||
362 | throw $e; |
||
363 | } |
||
364 | } |
||
365 | |||
366 | $this->collection->update($criteria, array('$set' => new \stdClass), $options); |
||
367 | } |
||
368 | |||
369 | /** |
||
370 | * Updates the already persisted document if it has any new changesets. |
||
371 | * |
||
372 | * @param object $document |
||
373 | * @param array $options Array of options to be used with update() |
||
374 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
375 | */ |
||
376 | 227 | public function update($document, array $options = array()) |
|
377 | { |
||
378 | 227 | $update = $this->pb->prepareUpdateData($document); |
|
379 | |||
380 | 227 | $query = $this->getQueryForDocument($document); |
|
381 | |||
382 | 225 | foreach (array_keys($query) as $field) { |
|
383 | 225 | unset($update['$set'][$field]); |
|
384 | } |
||
385 | |||
386 | 225 | if (empty($update['$set'])) { |
|
387 | 94 | unset($update['$set']); |
|
388 | } |
||
389 | |||
390 | |||
391 | // Include versioning logic to set the new version value in the database |
||
392 | // and to ensure the version has not changed since this document object instance |
||
393 | // was fetched from the database |
||
394 | 225 | $nextVersion = null; |
|
395 | 225 | if ($this->class->isVersioned) { |
|
396 | 33 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
397 | 33 | $currentVersion = $this->class->reflFields[$this->class->versionField]->getValue($document); |
|
398 | 33 | if ($versionMapping['type'] === 'int') { |
|
399 | 30 | $nextVersion = $currentVersion + 1; |
|
400 | 30 | $update['$inc'][$versionMapping['name']] = 1; |
|
401 | 30 | $query[$versionMapping['name']] = $currentVersion; |
|
402 | 3 | } elseif ($versionMapping['type'] === 'date') { |
|
403 | 3 | $nextVersion = new \DateTime(); |
|
404 | 3 | $update['$set'][$versionMapping['name']] = new \MongoDate($nextVersion->getTimestamp()); |
|
405 | 3 | $query[$versionMapping['name']] = new \MongoDate($currentVersion->getTimestamp()); |
|
406 | } |
||
407 | } |
||
408 | |||
409 | 225 | if ( ! empty($update)) { |
|
410 | // Include locking logic so that if the document object in memory is currently |
||
411 | // locked then it will remove it, otherwise it ensures the document is not locked. |
||
412 | 157 | if ($this->class->isLockable) { |
|
413 | 11 | $isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document); |
|
414 | 11 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
415 | 11 | if ($isLocked) { |
|
416 | 2 | $update['$unset'] = array($lockMapping['name'] => true); |
|
417 | } else { |
||
418 | 9 | $query[$lockMapping['name']] = array('$exists' => false); |
|
419 | } |
||
420 | } |
||
421 | |||
422 | 157 | $options = $this->getWriteOptions($options); |
|
423 | |||
424 | 157 | $result = $this->collection->update($query, $update, $options); |
|
425 | |||
426 | 157 | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
|
427 | 6 | throw LockException::lockFailed($document); |
|
428 | 152 | } elseif ($this->class->isVersioned) { |
|
429 | 28 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
430 | } |
||
431 | } |
||
432 | |||
433 | 220 | $this->handleCollections($document, $options); |
|
434 | 220 | } |
|
435 | |||
436 | /** |
||
437 | * Removes document from mongo |
||
438 | * |
||
439 | * @param mixed $document |
||
440 | * @param array $options Array of options to be used with remove() |
||
441 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
442 | */ |
||
443 | 35 | public function delete($document, array $options = array()) |
|
444 | { |
||
445 | 35 | $query = $this->getQueryForDocument($document); |
|
446 | |||
447 | 35 | if ($this->class->isLockable) { |
|
448 | 2 | $query[$this->class->lockField] = array('$exists' => false); |
|
449 | } |
||
450 | |||
451 | 35 | $options = $this->getWriteOptions($options); |
|
452 | |||
453 | 35 | $result = $this->collection->remove($query, $options); |
|
454 | |||
455 | 35 | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
|
456 | 2 | throw LockException::lockFailed($document); |
|
457 | } |
||
458 | 33 | } |
|
459 | |||
460 | /** |
||
461 | * Refreshes a managed document. |
||
462 | * |
||
463 | * @param string $id |
||
464 | * @param object $document The document to refresh. |
||
465 | * |
||
466 | * @deprecated The first argument is deprecated. |
||
467 | */ |
||
468 | 22 | public function refresh($id, $document) |
|
469 | { |
||
470 | 22 | $query = $this->getQueryForDocument($document); |
|
471 | 22 | $data = $this->collection->findOne($query); |
|
472 | 22 | $data = $this->hydratorFactory->hydrate($document, $data); |
|
473 | 22 | $this->uow->setOriginalDocumentData($document, $data); |
|
474 | 22 | } |
|
475 | |||
476 | /** |
||
477 | * Finds a document by a set of criteria. |
||
478 | * |
||
479 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
480 | * match an _id value. |
||
481 | * |
||
482 | * @param mixed $criteria Query criteria |
||
483 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
484 | * @param array $hints Hints for document creation |
||
485 | * @param integer $lockMode |
||
486 | * @param array $sort Sort array for Cursor::sort() |
||
487 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
488 | * @return object|null The loaded and managed document instance or null if no document was found |
||
489 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
490 | */ |
||
491 | 384 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
492 | { |
||
493 | // TODO: remove this |
||
494 | 384 | if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoId) { |
|
495 | $criteria = array('_id' => $criteria); |
||
496 | } |
||
497 | |||
498 | 384 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
499 | 384 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
500 | 384 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
501 | |||
502 | 384 | $cursor = $this->collection->find($criteria); |
|
503 | |||
504 | 384 | if (null !== $sort) { |
|
505 | 105 | $cursor->sort($this->prepareSortOrProjection($sort)); |
|
506 | } |
||
507 | |||
508 | 384 | $result = $cursor->getSingleResult(); |
|
509 | |||
510 | 384 | if ($this->class->isLockable) { |
|
511 | 1 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
512 | 1 | if (isset($result[$lockMapping['name']]) && $result[$lockMapping['name']] === LockMode::PESSIMISTIC_WRITE) { |
|
513 | 1 | throw LockException::lockFailed($result); |
|
514 | } |
||
515 | } |
||
516 | |||
517 | 383 | return $this->createDocument($result, $document, $hints); |
|
518 | } |
||
519 | |||
520 | /** |
||
521 | * Finds documents by a set of criteria. |
||
522 | * |
||
523 | * @param array $criteria Query criteria |
||
524 | * @param array $sort Sort array for Cursor::sort() |
||
525 | * @param integer|null $limit Limit for Cursor::limit() |
||
526 | * @param integer|null $skip Skip for Cursor::skip() |
||
527 | * @return Cursor |
||
528 | */ |
||
529 | 26 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
530 | { |
||
531 | 26 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
532 | 26 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
533 | 26 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
534 | |||
535 | 26 | $baseCursor = $this->collection->find($criteria); |
|
536 | 26 | $cursor = $this->wrapCursor($baseCursor); |
|
537 | |||
538 | 26 | if (null !== $sort) { |
|
539 | 3 | $cursor->sort($sort); |
|
540 | } |
||
541 | |||
542 | 26 | if (null !== $limit) { |
|
543 | 2 | $cursor->limit($limit); |
|
544 | } |
||
545 | |||
546 | 26 | if (null !== $skip) { |
|
547 | 2 | $cursor->skip($skip); |
|
548 | } |
||
549 | |||
550 | 26 | return $cursor; |
|
551 | } |
||
552 | |||
553 | /** |
||
554 | * @param object $document |
||
555 | * |
||
556 | * @return array |
||
557 | * @throws MongoDBException |
||
558 | */ |
||
559 | 307 | private function getShardKeyQuery($document) |
|
560 | { |
||
561 | 307 | if ( ! $this->class->isSharded()) { |
|
562 | 298 | return array(); |
|
563 | } |
||
564 | |||
565 | 9 | $shardKey = $this->class->getShardKey(); |
|
566 | 9 | $keys = array_keys($shardKey['keys']); |
|
567 | 9 | $data = $this->uow->getDocumentActualData($document); |
|
568 | |||
569 | 9 | $shardKeyQueryPart = array(); |
|
570 | 9 | foreach ($keys as $key) { |
|
571 | 9 | $mapping = $this->class->getFieldMappingByDbFieldName($key); |
|
572 | 9 | $this->guardMissingShardKey($document, $key, $data); |
|
573 | 7 | $value = Type::getType($mapping['type'])->convertToDatabaseValue($data[$mapping['fieldName']]); |
|
574 | 7 | $shardKeyQueryPart[$key] = $value; |
|
575 | } |
||
576 | |||
577 | 7 | return $shardKeyQueryPart; |
|
578 | } |
||
579 | |||
580 | /** |
||
581 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
582 | * |
||
583 | * @param CursorInterface $baseCursor |
||
584 | * @return Cursor |
||
585 | */ |
||
586 | 26 | private function wrapCursor(CursorInterface $baseCursor) |
|
587 | { |
||
588 | 26 | return new Cursor($baseCursor, $this->dm->getUnitOfWork(), $this->class); |
|
589 | } |
||
590 | |||
591 | /** |
||
592 | * Checks whether the given managed document exists in the database. |
||
593 | * |
||
594 | * @param object $document |
||
595 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
596 | */ |
||
597 | 3 | public function exists($document) |
|
598 | { |
||
599 | 3 | $id = $this->class->getIdentifierObject($document); |
|
600 | 3 | return (boolean) $this->collection->findOne(array('_id' => $id), array('_id')); |
|
601 | } |
||
602 | |||
603 | /** |
||
604 | * Locks document by storing the lock mode on the mapped lock field. |
||
605 | * |
||
606 | * @param object $document |
||
607 | * @param int $lockMode |
||
608 | */ |
||
609 | 5 | public function lock($document, $lockMode) |
|
610 | { |
||
611 | 5 | $id = $this->uow->getDocumentIdentifier($document); |
|
612 | 5 | $criteria = array('_id' => $this->class->getDatabaseIdentifierValue($id)); |
|
613 | 5 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
614 | 5 | $this->collection->update($criteria, array('$set' => array($lockMapping['name'] => $lockMode))); |
|
615 | 5 | $this->class->reflFields[$this->class->lockField]->setValue($document, $lockMode); |
|
616 | 5 | } |
|
617 | |||
618 | /** |
||
619 | * Releases any lock that exists on this document. |
||
620 | * |
||
621 | * @param object $document |
||
622 | */ |
||
623 | 1 | public function unlock($document) |
|
624 | { |
||
625 | 1 | $id = $this->uow->getDocumentIdentifier($document); |
|
626 | 1 | $criteria = array('_id' => $this->class->getDatabaseIdentifierValue($id)); |
|
627 | 1 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
628 | 1 | $this->collection->update($criteria, array('$unset' => array($lockMapping['name'] => true))); |
|
629 | 1 | $this->class->reflFields[$this->class->lockField]->setValue($document, null); |
|
630 | 1 | } |
|
631 | |||
632 | /** |
||
633 | * Creates or fills a single document object from an query result. |
||
634 | * |
||
635 | * @param object $result The query result. |
||
636 | * @param object $document The document object to fill, if any. |
||
637 | * @param array $hints Hints for document creation. |
||
638 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
639 | */ |
||
640 | 383 | private function createDocument($result, $document = null, array $hints = array()) |
|
641 | { |
||
642 | 383 | if ($result === null) { |
|
643 | 126 | return null; |
|
644 | } |
||
645 | |||
646 | 330 | if ($document !== null) { |
|
647 | 38 | $hints[Query::HINT_REFRESH] = true; |
|
648 | 38 | $id = $this->class->getPHPIdentifierValue($result['_id']); |
|
649 | 38 | $this->uow->registerManaged($document, $id, $result); |
|
650 | } |
||
651 | |||
652 | 330 | return $this->uow->getOrCreateDocument($this->class->name, $result, $hints, $document); |
|
653 | } |
||
654 | |||
655 | /** |
||
656 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
657 | * |
||
658 | * @param PersistentCollectionInterface $collection |
||
659 | */ |
||
660 | 173 | public function loadCollection(PersistentCollectionInterface $collection) |
|
661 | { |
||
662 | 173 | $mapping = $collection->getMapping(); |
|
663 | 173 | switch ($mapping['association']) { |
|
664 | case ClassMetadata::EMBED_MANY: |
||
665 | 119 | $this->loadEmbedManyCollection($collection); |
|
666 | 119 | break; |
|
667 | |||
668 | case ClassMetadata::REFERENCE_MANY: |
||
669 | 71 | if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) { |
|
670 | 5 | $this->loadReferenceManyWithRepositoryMethod($collection); |
|
671 | } else { |
||
672 | 66 | if ($mapping['isOwningSide']) { |
|
673 | 55 | $this->loadReferenceManyCollectionOwningSide($collection); |
|
674 | } else { |
||
675 | 15 | $this->loadReferenceManyCollectionInverseSide($collection); |
|
676 | } |
||
677 | } |
||
678 | 70 | break; |
|
679 | } |
||
680 | 172 | } |
|
681 | |||
682 | 119 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
683 | { |
||
684 | 119 | $embeddedDocuments = $collection->getMongoData(); |
|
685 | 119 | $mapping = $collection->getMapping(); |
|
686 | 119 | $owner = $collection->getOwner(); |
|
687 | 119 | if ($embeddedDocuments) { |
|
688 | 90 | foreach ($embeddedDocuments as $key => $embeddedDocument) { |
|
689 | 90 | $className = $this->uow->getClassNameForAssociation($mapping, $embeddedDocument); |
|
690 | 90 | $embeddedMetadata = $this->dm->getClassMetadata($className); |
|
691 | 90 | $embeddedDocumentObject = $embeddedMetadata->newInstance(); |
|
692 | |||
693 | 90 | $this->uow->setParentAssociation($embeddedDocumentObject, $mapping, $owner, $mapping['name'] . '.' . $key); |
|
694 | |||
695 | 90 | $data = $this->hydratorFactory->hydrate($embeddedDocumentObject, $embeddedDocument, $collection->getHints()); |
|
696 | 90 | $id = $embeddedMetadata->identifier && isset($data[$embeddedMetadata->identifier]) |
|
697 | 23 | ? $data[$embeddedMetadata->identifier] |
|
698 | 90 | : null; |
|
699 | |||
700 | 90 | if (empty($collection->getHints()[Query::HINT_READ_ONLY])) { |
|
701 | 89 | $this->uow->registerManaged($embeddedDocumentObject, $id, $data); |
|
702 | } |
||
703 | 90 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
704 | 25 | $collection->set($key, $embeddedDocumentObject); |
|
705 | } else { |
||
706 | 90 | $collection->add($embeddedDocumentObject); |
|
707 | } |
||
708 | } |
||
709 | } |
||
710 | 119 | } |
|
711 | |||
712 | 55 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
713 | { |
||
714 | 55 | $hints = $collection->getHints(); |
|
715 | 55 | $mapping = $collection->getMapping(); |
|
716 | 55 | $groupedIds = array(); |
|
717 | |||
718 | 55 | $sorted = isset($mapping['sort']) && $mapping['sort']; |
|
719 | |||
720 | 55 | foreach ($collection->getMongoData() as $key => $reference) { |
|
721 | 50 | $className = $this->uow->getClassNameForAssociation($mapping, $reference); |
|
722 | 50 | $mongoId = ClassMetadataInfo::getReferenceId($reference, $mapping['storeAs']); |
|
723 | 50 | $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($mongoId); |
|
724 | |||
725 | // create a reference to the class and id |
||
726 | 50 | $reference = $this->dm->getReference($className, $id); |
|
727 | |||
728 | // no custom sort so add the references right now in the order they are embedded |
||
729 | 50 | if ( ! $sorted) { |
|
730 | 49 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
731 | 2 | $collection->set($key, $reference); |
|
732 | } else { |
||
733 | 47 | $collection->add($reference); |
|
734 | } |
||
735 | } |
||
736 | |||
737 | // only query for the referenced object if it is not already initialized or the collection is sorted |
||
738 | 50 | if (($reference instanceof Proxy && ! $reference->__isInitialized__) || $sorted) { |
|
739 | 50 | $groupedIds[$className][] = $mongoId; |
|
740 | } |
||
741 | } |
||
742 | 55 | foreach ($groupedIds as $className => $ids) { |
|
743 | 35 | $class = $this->dm->getClassMetadata($className); |
|
744 | 35 | $mongoCollection = $this->dm->getDocumentCollection($className); |
|
745 | 35 | $criteria = $this->cm->merge( |
|
746 | 35 | array('_id' => array('$in' => array_values($ids))), |
|
747 | 35 | $this->dm->getFilterCollection()->getFilterCriteria($class), |
|
748 | 35 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
749 | ); |
||
750 | 35 | $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); |
|
751 | 35 | $cursor = $mongoCollection->find($criteria); |
|
752 | 35 | if (isset($mapping['sort'])) { |
|
753 | 35 | $cursor->sort($mapping['sort']); |
|
754 | } |
||
755 | 35 | if (isset($mapping['limit'])) { |
|
756 | $cursor->limit($mapping['limit']); |
||
757 | } |
||
758 | 35 | if (isset($mapping['skip'])) { |
|
759 | $cursor->skip($mapping['skip']); |
||
760 | } |
||
761 | 35 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
762 | $cursor->slaveOkay(true); |
||
763 | } |
||
764 | 35 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
765 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
766 | } |
||
767 | 35 | $documents = $cursor->toArray(false); |
|
768 | 35 | foreach ($documents as $documentData) { |
|
769 | 34 | $document = $this->uow->getById($documentData['_id'], $class); |
|
770 | 34 | if ($document instanceof Proxy && ! $document->__isInitialized()) { |
|
771 | 34 | $data = $this->hydratorFactory->hydrate($document, $documentData); |
|
772 | 34 | $this->uow->setOriginalDocumentData($document, $data); |
|
773 | 34 | $document->__isInitialized__ = true; |
|
774 | } |
||
775 | 34 | if ($sorted) { |
|
776 | 35 | $collection->add($document); |
|
777 | } |
||
778 | } |
||
779 | } |
||
780 | 55 | } |
|
781 | |||
782 | 15 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
790 | |||
791 | /** |
||
792 | * @param PersistentCollectionInterface $collection |
||
793 | * |
||
794 | * @return Query |
||
795 | */ |
||
796 | 18 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
797 | { |
||
798 | 18 | $hints = $collection->getHints(); |
|
799 | 18 | $mapping = $collection->getMapping(); |
|
800 | 18 | $owner = $collection->getOwner(); |
|
801 | 18 | $ownerClass = $this->dm->getClassMetadata(get_class($owner)); |
|
802 | 18 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
803 | 18 | $mappedByMapping = isset($targetClass->fieldMappings[$mapping['mappedBy']]) ? $targetClass->fieldMappings[$mapping['mappedBy']] : array(); |
|
804 | 18 | $mappedByFieldName = ClassMetadataInfo::getReferenceFieldName(isset($mappedByMapping['storeAs']) ? $mappedByMapping['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF, $mapping['mappedBy']); |
|
805 | |||
806 | 18 | $criteria = $this->cm->merge( |
|
807 | 18 | array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), |
|
808 | 18 | $this->dm->getFilterCollection()->getFilterCriteria($targetClass), |
|
809 | 18 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
810 | ); |
||
811 | 18 | $criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria); |
|
812 | 18 | $qb = $this->dm->createQueryBuilder($mapping['targetDocument']) |
|
813 | 18 | ->setQueryArray($criteria); |
|
814 | |||
836 | |||
837 | 5 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
850 | |||
851 | /** |
||
852 | * @param PersistentCollectionInterface $collection |
||
853 | * |
||
854 | * @return CursorInterface |
||
855 | */ |
||
856 | 6 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
897 | |||
898 | /** |
||
899 | * Prepare a sort or projection array by converting keys, which are PHP |
||
900 | * property names, to MongoDB field names. |
||
901 | * |
||
902 | * @param array $fields |
||
903 | * @return array |
||
904 | */ |
||
905 | 145 | public function prepareSortOrProjection(array $fields) |
|
915 | |||
916 | /** |
||
917 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
918 | * |
||
919 | * @param string $fieldName |
||
920 | * @return string |
||
921 | */ |
||
922 | 112 | public function prepareFieldName($fieldName) |
|
928 | |||
929 | /** |
||
930 | * Adds discriminator criteria to an already-prepared query. |
||
931 | * |
||
932 | * This method should be used once for query criteria and not be used for |
||
933 | * nested expressions. It should be called before |
||
934 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
935 | * |
||
936 | * @param array $preparedQuery |
||
937 | * @return array |
||
938 | */ |
||
939 | 545 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
955 | |||
956 | /** |
||
957 | * Adds filter 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 after |
||
961 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
962 | * |
||
963 | * @param array $preparedQuery |
||
964 | * @return array |
||
965 | */ |
||
966 | 546 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
980 | |||
981 | /** |
||
982 | * Prepares the query criteria or new document object. |
||
983 | * |
||
984 | * PHP field names and types will be converted to those used by MongoDB. |
||
985 | * |
||
986 | * @param array $query |
||
987 | * @param bool $isNewObj |
||
988 | * @return array |
||
989 | */ |
||
990 | 570 | public function prepareQueryOrNewObj(array $query, $isNewObj = false) |
|
1018 | |||
1019 | /** |
||
1020 | * Prepares a query value and converts the PHP value to the database value |
||
1021 | * if it is an identifier. |
||
1022 | * |
||
1023 | * It also handles converting $fieldName to the database name if they are different. |
||
1024 | * |
||
1025 | * @param string $fieldName |
||
1026 | * @param mixed $value |
||
1027 | * @param ClassMetadata $class Defaults to $this->class |
||
1028 | * @param bool $prepareValue Whether or not to prepare the value |
||
1029 | * @param bool $inNewObj Whether or not newObj is being prepared |
||
1030 | * @return array An array of tuples containing prepared field names and values |
||
1031 | */ |
||
1032 | 575 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true, $inNewObj = false) |
|
1219 | |||
1220 | /** |
||
1221 | * Prepares a query expression. |
||
1222 | * |
||
1223 | * @param array|object $expression |
||
1224 | * @param ClassMetadata $class |
||
1225 | * @return array |
||
1226 | */ |
||
1227 | 75 | private function prepareQueryExpression($expression, $class) |
|
1254 | |||
1255 | /** |
||
1256 | * Checks whether the value has DBRef fields. |
||
1257 | * |
||
1258 | * This method doesn't check if the the value is a complete DBRef object, |
||
1259 | * although it should return true for a DBRef. Rather, we're checking that |
||
1260 | * the value has one or more fields for a DBref. In practice, this could be |
||
1261 | * $elemMatch criteria for matching a DBRef. |
||
1262 | * |
||
1263 | * @param mixed $value |
||
1264 | * @return boolean |
||
1265 | */ |
||
1266 | 76 | private function hasDBRefFields($value) |
|
1284 | |||
1285 | /** |
||
1286 | * Checks whether the value has query operators. |
||
1287 | * |
||
1288 | * @param mixed $value |
||
1289 | * @return boolean |
||
1290 | */ |
||
1291 | 80 | private function hasQueryOperators($value) |
|
1309 | |||
1310 | /** |
||
1311 | * Gets the array of discriminator values for the given ClassMetadata |
||
1312 | * |
||
1313 | * @param ClassMetadata $metadata |
||
1314 | * @return array |
||
1315 | */ |
||
1316 | 29 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1332 | |||
1333 | 627 | private function handleCollections($document, $options) |
|
1352 | |||
1353 | /** |
||
1354 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
1355 | * Also, shard key field should be present in actual document data. |
||
1356 | * |
||
1357 | * @param object $document |
||
1358 | * @param string $shardKeyField |
||
1359 | * @param array $actualDocumentData |
||
1360 | * |
||
1361 | * @throws MongoDBException |
||
1362 | */ |
||
1363 | 9 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
1379 | |||
1380 | /** |
||
1381 | * Get shard key aware query for single document. |
||
1382 | * |
||
1383 | * @param object $document |
||
1384 | * |
||
1385 | * @return array |
||
1386 | */ |
||
1387 | 304 | private function getQueryForDocument($document) |
|
1397 | |||
1398 | /** |
||
1399 | * @param array $options |
||
1400 | * |
||
1401 | * @return array |
||
1402 | */ |
||
1403 | 629 | private function getWriteOptions(array $options = array()) |
|
1413 | |||
1414 | /** |
||
1415 | * @param string $fieldName |
||
1416 | * @param mixed $value |
||
1417 | * @param array $mapping |
||
1418 | * @param bool $inNewObj |
||
1419 | * @return array |
||
1420 | */ |
||
1421 | 14 | private function prepareReference($fieldName, $value, array $mapping, $inNewObj) |
|
1461 | } |
||
1462 |
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: