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 | 749 | public function __construct( |
|
150 | |||
151 | /** |
||
152 | * @return array |
||
153 | */ |
||
154 | public function getInserts() |
||
158 | |||
159 | /** |
||
160 | * @param object $document |
||
161 | * @return bool |
||
162 | */ |
||
163 | public function isQueuedForInsert($document) |
||
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 | 523 | public function addInsert($document) |
|
178 | |||
179 | /** |
||
180 | * @return array |
||
181 | */ |
||
182 | public function getUpserts() |
||
186 | |||
187 | /** |
||
188 | * @param object $document |
||
189 | * @return boolean |
||
190 | */ |
||
191 | public function isQueuedForUpsert($document) |
||
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 | 86 | public function addUpsert($document) |
|
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() |
||
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 | 523 | public function executeInserts(array $options = array()) |
|
228 | { |
||
229 | 523 | if ( ! $this->queuedInserts) { |
|
230 | return; |
||
231 | } |
||
232 | |||
233 | 523 | $inserts = array(); |
|
234 | 523 | $options = $this->getWriteOptions($options); |
|
235 | 523 | foreach ($this->queuedInserts as $oid => $document) { |
|
236 | 523 | $data = $this->pb->prepareInsertData($document); |
|
237 | |||
238 | // Set the initial version for each insert |
||
239 | 522 | 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 | 39 | } 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 | 2 | } |
|
249 | 39 | $data[$versionMapping['name']] = $nextVersion; |
|
250 | 39 | } |
|
251 | |||
252 | 522 | $inserts[$oid] = $data; |
|
253 | 522 | } |
|
254 | |||
255 | 522 | if ($inserts) { |
|
256 | try { |
||
257 | 522 | $this->collection->batchInsert($inserts, $options); |
|
258 | 522 | } catch (\MongoException $e) { |
|
259 | 7 | $this->queuedInserts = array(); |
|
260 | 7 | throw $e; |
|
261 | } |
||
262 | 522 | } |
|
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 | 522 | foreach ($this->queuedInserts as $document) { |
|
269 | 522 | $this->handleCollections($document, $options); |
|
270 | 522 | } |
|
271 | |||
272 | 522 | $this->queuedInserts = array(); |
|
273 | 522 | } |
|
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 | 86 | public function executeUpserts(array $options = array()) |
|
285 | { |
||
286 | 86 | if ( ! $this->queuedUpserts) { |
|
287 | return; |
||
288 | } |
||
289 | |||
290 | 86 | $options = $this->getWriteOptions($options); |
|
291 | 86 | foreach ($this->queuedUpserts as $oid => $document) { |
|
292 | try { |
||
293 | 86 | $this->executeUpsert($document, $options); |
|
294 | 86 | $this->handleCollections($document, $options); |
|
295 | 86 | unset($this->queuedUpserts[$oid]); |
|
296 | 86 | } catch (\MongoException $e) { |
|
297 | unset($this->queuedUpserts[$oid]); |
||
298 | throw $e; |
||
299 | } |
||
300 | 86 | } |
|
301 | 86 | } |
|
302 | |||
303 | /** |
||
304 | * Executes a single upsert in {@link executeUpserts} |
||
305 | * |
||
306 | * @param object $document |
||
307 | * @param array $options |
||
308 | */ |
||
309 | 86 | private function executeUpsert($document, array $options) |
|
310 | { |
||
311 | 86 | $options['upsert'] = true; |
|
312 | 86 | $criteria = $this->getQueryForDocument($document); |
|
313 | |||
314 | 86 | $data = $this->pb->prepareUpsertData($document); |
|
315 | |||
316 | // Set the initial version for each upsert |
||
317 | 86 | 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 | 3 | } 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 | 1 | } |
|
327 | 3 | $data['$set'][$versionMapping['name']] = $nextVersion; |
|
328 | 3 | } |
|
329 | |||
330 | 86 | foreach (array_keys($criteria) as $field) { |
|
331 | 86 | unset($data['$set'][$field]); |
|
332 | 86 | } |
|
333 | |||
334 | // Do not send an empty $set modifier |
||
335 | 86 | if (empty($data['$set'])) { |
|
336 | 17 | unset($data['$set']); |
|
337 | 17 | } |
|
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 | 86 | if (empty($data)) { |
|
353 | 17 | $retry = true; |
|
354 | 17 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
355 | 17 | } |
|
356 | |||
357 | try { |
||
358 | 86 | $this->collection->update($criteria, $data, $options); |
|
359 | 86 | 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 | 222 | public function update($document, array $options = array()) |
|
377 | { |
||
378 | 222 | $update = $this->pb->prepareUpdateData($document); |
|
379 | |||
380 | 222 | $query = $this->getQueryForDocument($document); |
|
381 | |||
382 | 222 | foreach (array_keys($query) as $field) { |
|
383 | 222 | unset($update['$set'][$field]); |
|
384 | 222 | } |
|
385 | |||
386 | 222 | if (empty($update['$set'])) { |
|
387 | 94 | unset($update['$set']); |
|
388 | 94 | } |
|
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 | 222 | if ($this->class->isVersioned) { |
|
395 | 31 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
396 | 31 | $currentVersion = $this->class->reflFields[$this->class->versionField]->getValue($document); |
|
397 | 31 | if ($versionMapping['type'] === 'int') { |
|
398 | 28 | $nextVersion = $currentVersion + 1; |
|
399 | 28 | $update['$inc'][$versionMapping['name']] = 1; |
|
400 | 28 | $query[$versionMapping['name']] = $currentVersion; |
|
401 | 28 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
402 | 31 | } 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 | 3 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
407 | 3 | } |
|
408 | 31 | } |
|
409 | |||
410 | 222 | if ( ! empty($update)) { |
|
411 | // Include locking logic so that if the document object in memory is currently |
||
412 | // locked then it will remove it, otherwise it ensures the document is not locked. |
||
413 | 154 | if ($this->class->isLockable) { |
|
414 | 11 | $isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document); |
|
415 | 11 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
416 | 11 | if ($isLocked) { |
|
417 | 2 | $update['$unset'] = array($lockMapping['name'] => true); |
|
418 | 2 | } else { |
|
419 | 9 | $query[$lockMapping['name']] = array('$exists' => false); |
|
420 | } |
||
421 | 11 | } |
|
422 | |||
423 | 154 | $options = $this->getWriteOptions($options); |
|
424 | |||
425 | 154 | $result = $this->collection->update($query, $update, $options); |
|
426 | |||
427 | 154 | View Code Duplication | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
428 | 5 | throw LockException::lockFailed($document); |
|
429 | } |
||
430 | 150 | } |
|
431 | |||
432 | 218 | $this->handleCollections($document, $options); |
|
433 | 218 | } |
|
434 | |||
435 | /** |
||
436 | * Removes document from mongo |
||
437 | * |
||
438 | * @param mixed $document |
||
439 | * @param array $options Array of options to be used with remove() |
||
440 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
441 | */ |
||
442 | 33 | public function delete($document, array $options = array()) |
|
443 | { |
||
444 | 33 | $query = $this->getQueryForDocument($document); |
|
445 | |||
446 | 33 | if ($this->class->isLockable) { |
|
447 | 2 | $query[$this->class->lockField] = array('$exists' => false); |
|
448 | 2 | } |
|
449 | |||
450 | 33 | $options = $this->getWriteOptions($options); |
|
451 | |||
452 | 33 | $result = $this->collection->remove($query, $options); |
|
453 | |||
454 | 33 | View Code Duplication | if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) { |
455 | 2 | throw LockException::lockFailed($document); |
|
456 | } |
||
457 | 31 | } |
|
458 | |||
459 | /** |
||
460 | * Refreshes a managed document. |
||
461 | * |
||
462 | * @param string $id |
||
463 | * @param object $document The document to refresh. |
||
464 | * |
||
465 | * @deprecated The first argument is deprecated. |
||
466 | */ |
||
467 | 22 | public function refresh($id, $document) |
|
474 | |||
475 | /** |
||
476 | * Finds a document by a set of criteria. |
||
477 | * |
||
478 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
479 | * match an _id value. |
||
480 | * |
||
481 | * @param mixed $criteria Query criteria |
||
482 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
483 | * @param array $hints Hints for document creation |
||
484 | * @param integer $lockMode |
||
485 | * @param array $sort Sort array for Cursor::sort() |
||
486 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
487 | * @return object|null The loaded and managed document instance or null if no document was found |
||
488 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
489 | */ |
||
490 | 379 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
491 | { |
||
492 | // TODO: remove this |
||
493 | 379 | if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoId) { |
|
494 | $criteria = array('_id' => $criteria); |
||
495 | } |
||
496 | |||
497 | 379 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
498 | 379 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
499 | 379 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
500 | |||
501 | 379 | $cursor = $this->collection->find($criteria); |
|
502 | |||
503 | 379 | if (null !== $sort) { |
|
504 | 105 | $cursor->sort($this->prepareSortOrProjection($sort)); |
|
505 | 105 | } |
|
506 | |||
507 | 379 | $result = $cursor->getSingleResult(); |
|
508 | |||
509 | 379 | 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 | 378 | 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 Cursor |
||
527 | */ |
||
528 | 26 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
529 | { |
||
530 | 26 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
531 | 26 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
532 | 26 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
533 | |||
534 | 26 | $baseCursor = $this->collection->find($criteria); |
|
535 | 26 | $cursor = $this->wrapCursor($baseCursor); |
|
536 | |||
537 | 26 | if (null !== $sort) { |
|
538 | 3 | $cursor->sort($sort); |
|
539 | 3 | } |
|
540 | |||
541 | 26 | if (null !== $limit) { |
|
542 | 2 | $cursor->limit($limit); |
|
543 | 2 | } |
|
544 | |||
545 | 26 | if (null !== $skip) { |
|
546 | 2 | $cursor->skip($skip); |
|
547 | 2 | } |
|
548 | |||
549 | 26 | return $cursor; |
|
550 | } |
||
551 | |||
552 | /** |
||
553 | * @param object $document |
||
554 | * |
||
555 | * @return array |
||
556 | * @throws MongoDBException |
||
557 | */ |
||
558 | 297 | private function getShardKeyQuery($document) |
|
559 | { |
||
560 | 297 | if ( ! $this->class->isSharded()) { |
|
561 | 294 | return array(); |
|
562 | } |
||
563 | |||
564 | 3 | $shardKey = $this->class->getShardKey(); |
|
565 | 3 | $keys = array_keys($shardKey['keys']); |
|
566 | 3 | $data = $this->uow->getDocumentActualData($document); |
|
567 | |||
568 | 3 | $shardKeyQueryPart = array(); |
|
569 | 3 | foreach ($keys as $key) { |
|
570 | 3 | $mapping = $this->class->getFieldMappingByDbFieldName($key); |
|
571 | 3 | $this->guardMissingShardKey($document, $key, $data); |
|
572 | 3 | $value = Type::getType($mapping['type'])->convertToDatabaseValue($data[$mapping['fieldName']]); |
|
573 | 3 | $shardKeyQueryPart[$key] = $value; |
|
574 | 3 | } |
|
575 | |||
576 | 3 | return $shardKeyQueryPart; |
|
577 | } |
||
578 | |||
579 | /** |
||
580 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
581 | * |
||
582 | * @param CursorInterface $baseCursor |
||
583 | * @return Cursor |
||
584 | */ |
||
585 | 26 | private function wrapCursor(CursorInterface $baseCursor) |
|
589 | |||
590 | /** |
||
591 | * Checks whether the given managed document exists in the database. |
||
592 | * |
||
593 | * @param object $document |
||
594 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
595 | */ |
||
596 | 3 | public function exists($document) |
|
601 | |||
602 | /** |
||
603 | * Locks document by storing the lock mode on the mapped lock field. |
||
604 | * |
||
605 | * @param object $document |
||
606 | * @param int $lockMode |
||
607 | */ |
||
608 | 5 | public function lock($document, $lockMode) |
|
616 | |||
617 | /** |
||
618 | * Releases any lock that exists on this document. |
||
619 | * |
||
620 | * @param object $document |
||
621 | */ |
||
622 | 1 | public function unlock($document) |
|
630 | |||
631 | /** |
||
632 | * Creates or fills a single document object from an query result. |
||
633 | * |
||
634 | * @param object $result The query result. |
||
635 | * @param object $document The document object to fill, if any. |
||
636 | * @param array $hints Hints for document creation. |
||
637 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
638 | */ |
||
639 | 378 | private function createDocument($result, $document = null, array $hints = array()) |
|
640 | { |
||
641 | 378 | if ($result === null) { |
|
642 | 120 | return null; |
|
643 | } |
||
644 | |||
645 | 325 | if ($document !== null) { |
|
646 | 38 | $hints[Query::HINT_REFRESH] = true; |
|
647 | 38 | $id = $this->class->getPHPIdentifierValue($result['_id']); |
|
648 | 38 | $this->uow->registerManaged($document, $id, $result); |
|
649 | 38 | } |
|
650 | |||
651 | 325 | return $this->uow->getOrCreateDocument($this->class->name, $result, $hints, $document); |
|
652 | } |
||
653 | |||
654 | /** |
||
655 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
656 | * |
||
657 | * @param PersistentCollectionInterface $collection |
||
658 | */ |
||
659 | 173 | public function loadCollection(PersistentCollectionInterface $collection) |
|
660 | { |
||
661 | 173 | $mapping = $collection->getMapping(); |
|
662 | 173 | switch ($mapping['association']) { |
|
663 | 173 | case ClassMetadata::EMBED_MANY: |
|
664 | 119 | $this->loadEmbedManyCollection($collection); |
|
665 | 119 | break; |
|
666 | |||
667 | 71 | case ClassMetadata::REFERENCE_MANY: |
|
668 | 71 | if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) { |
|
669 | 5 | $this->loadReferenceManyWithRepositoryMethod($collection); |
|
670 | 4 | } else { |
|
671 | 66 | if ($mapping['isOwningSide']) { |
|
672 | 55 | $this->loadReferenceManyCollectionOwningSide($collection); |
|
673 | 55 | } else { |
|
674 | 15 | $this->loadReferenceManyCollectionInverseSide($collection); |
|
675 | } |
||
676 | } |
||
677 | 70 | break; |
|
678 | 172 | } |
|
679 | 172 | } |
|
680 | |||
681 | 119 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
682 | { |
||
683 | 119 | $embeddedDocuments = $collection->getMongoData(); |
|
684 | 119 | $mapping = $collection->getMapping(); |
|
685 | 119 | $owner = $collection->getOwner(); |
|
686 | 119 | if ($embeddedDocuments) { |
|
687 | 90 | foreach ($embeddedDocuments as $key => $embeddedDocument) { |
|
688 | 90 | $className = $this->uow->getClassNameForAssociation($mapping, $embeddedDocument); |
|
689 | 90 | $embeddedMetadata = $this->dm->getClassMetadata($className); |
|
690 | 90 | $embeddedDocumentObject = $embeddedMetadata->newInstance(); |
|
691 | |||
692 | 90 | $this->uow->setParentAssociation($embeddedDocumentObject, $mapping, $owner, $mapping['name'] . '.' . $key); |
|
693 | |||
694 | 90 | $data = $this->hydratorFactory->hydrate($embeddedDocumentObject, $embeddedDocument, $collection->getHints()); |
|
695 | 90 | $id = $embeddedMetadata->identifier && isset($data[$embeddedMetadata->identifier]) |
|
696 | 90 | ? $data[$embeddedMetadata->identifier] |
|
697 | 90 | : null; |
|
698 | |||
699 | 90 | if (empty($collection->getHints()[Query::HINT_READ_ONLY])) { |
|
700 | 89 | $this->uow->registerManaged($embeddedDocumentObject, $id, $data); |
|
701 | 89 | } |
|
702 | 90 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
703 | 25 | $collection->set($key, $embeddedDocumentObject); |
|
704 | 25 | } else { |
|
705 | 72 | $collection->add($embeddedDocumentObject); |
|
706 | } |
||
707 | 90 | } |
|
708 | 90 | } |
|
709 | 119 | } |
|
710 | |||
711 | 55 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
712 | { |
||
713 | 55 | $hints = $collection->getHints(); |
|
714 | 55 | $mapping = $collection->getMapping(); |
|
715 | 55 | $groupedIds = array(); |
|
716 | |||
717 | 55 | $sorted = isset($mapping['sort']) && $mapping['sort']; |
|
718 | |||
719 | 55 | foreach ($collection->getMongoData() as $key => $reference) { |
|
720 | 50 | if (isset($mapping['storeAs']) && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID) { |
|
721 | 5 | $className = $mapping['targetDocument']; |
|
722 | 5 | $mongoId = $reference; |
|
723 | 5 | } else { |
|
724 | 46 | $className = $this->uow->getClassNameForAssociation($mapping, $reference); |
|
725 | 46 | $mongoId = $reference['$id']; |
|
726 | } |
||
727 | 50 | $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($mongoId); |
|
728 | |||
729 | // create a reference to the class and id |
||
730 | 50 | $reference = $this->dm->getReference($className, $id); |
|
731 | |||
732 | // no custom sort so add the references right now in the order they are embedded |
||
733 | 50 | if ( ! $sorted) { |
|
734 | 49 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
735 | 2 | $collection->set($key, $reference); |
|
736 | 2 | } else { |
|
737 | 47 | $collection->add($reference); |
|
738 | } |
||
739 | 49 | } |
|
740 | |||
741 | // only query for the referenced object if it is not already initialized or the collection is sorted |
||
742 | 50 | if (($reference instanceof Proxy && ! $reference->__isInitialized__) || $sorted) { |
|
743 | 35 | $groupedIds[$className][] = $mongoId; |
|
744 | 35 | } |
|
745 | 55 | } |
|
746 | 55 | foreach ($groupedIds as $className => $ids) { |
|
747 | 35 | $class = $this->dm->getClassMetadata($className); |
|
748 | 35 | $mongoCollection = $this->dm->getDocumentCollection($className); |
|
749 | 35 | $criteria = $this->cm->merge( |
|
750 | 35 | array('_id' => array('$in' => array_values($ids))), |
|
751 | 35 | $this->dm->getFilterCollection()->getFilterCriteria($class), |
|
752 | 35 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
753 | 35 | ); |
|
754 | 35 | $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); |
|
755 | 35 | $cursor = $mongoCollection->find($criteria); |
|
756 | 35 | if (isset($mapping['sort'])) { |
|
757 | 35 | $cursor->sort($mapping['sort']); |
|
758 | 35 | } |
|
759 | 35 | if (isset($mapping['limit'])) { |
|
760 | $cursor->limit($mapping['limit']); |
||
761 | } |
||
762 | 35 | if (isset($mapping['skip'])) { |
|
763 | $cursor->skip($mapping['skip']); |
||
764 | } |
||
765 | 35 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
766 | $cursor->slaveOkay(true); |
||
767 | } |
||
768 | 35 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
769 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
770 | } |
||
771 | 35 | $documents = $cursor->toArray(false); |
|
772 | 35 | foreach ($documents as $documentData) { |
|
773 | 34 | $document = $this->uow->getById($documentData['_id'], $class); |
|
774 | 34 | if ($document instanceof Proxy && ! $document->__isInitialized()) { |
|
775 | 35 | $data = $this->hydratorFactory->hydrate($document, $documentData); |
|
776 | 34 | $this->uow->setOriginalDocumentData($document, $data); |
|
777 | 34 | $document->__isInitialized__ = true; |
|
778 | 34 | } |
|
779 | 34 | if ($sorted) { |
|
780 | 1 | $collection->add($document); |
|
781 | 1 | } |
|
782 | 35 | } |
|
783 | 55 | } |
|
784 | 55 | } |
|
785 | |||
786 | 15 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
787 | { |
||
788 | 15 | $query = $this->createReferenceManyInverseSideQuery($collection); |
|
789 | 15 | $documents = $query->execute()->toArray(false); |
|
790 | 15 | foreach ($documents as $key => $document) { |
|
791 | 14 | $collection->add($document); |
|
792 | 15 | } |
|
793 | 15 | } |
|
794 | |||
795 | /** |
||
796 | * @param PersistentCollectionInterface $collection |
||
797 | * |
||
798 | * @return Query |
||
799 | */ |
||
800 | 18 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
801 | { |
||
802 | 18 | $hints = $collection->getHints(); |
|
803 | 18 | $mapping = $collection->getMapping(); |
|
804 | 18 | $owner = $collection->getOwner(); |
|
805 | 18 | $ownerClass = $this->dm->getClassMetadata(get_class($owner)); |
|
806 | 18 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
807 | 18 | $mappedByMapping = isset($targetClass->fieldMappings[$mapping['mappedBy']]) ? $targetClass->fieldMappings[$mapping['mappedBy']] : array(); |
|
808 | 18 | $mappedByFieldName = isset($mappedByMapping['storeAs']) && $mappedByMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID ? $mapping['mappedBy'] : $mapping['mappedBy'] . '.$id'; |
|
809 | 18 | $criteria = $this->cm->merge( |
|
810 | 18 | array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), |
|
811 | 18 | $this->dm->getFilterCollection()->getFilterCriteria($targetClass), |
|
812 | 18 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
813 | 18 | ); |
|
814 | 18 | $criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria); |
|
815 | 18 | $qb = $this->dm->createQueryBuilder($mapping['targetDocument']) |
|
816 | 18 | ->setQueryArray($criteria); |
|
817 | |||
818 | 18 | if (isset($mapping['sort'])) { |
|
819 | 18 | $qb->sort($mapping['sort']); |
|
820 | 18 | } |
|
821 | 18 | if (isset($mapping['limit'])) { |
|
822 | 2 | $qb->limit($mapping['limit']); |
|
823 | 2 | } |
|
824 | 18 | if (isset($mapping['skip'])) { |
|
825 | $qb->skip($mapping['skip']); |
||
826 | } |
||
827 | 18 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
828 | $qb->slaveOkay(true); |
||
829 | } |
||
830 | 18 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
831 | $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
832 | } |
||
833 | 18 | foreach ($mapping['prime'] as $field) { |
|
834 | 4 | $qb->field($field)->prime(true); |
|
835 | 18 | } |
|
836 | |||
837 | 18 | return $qb->getQuery(); |
|
838 | } |
||
839 | |||
840 | 5 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
841 | { |
||
842 | 5 | $cursor = $this->createReferenceManyWithRepositoryMethodCursor($collection); |
|
843 | 4 | $mapping = $collection->getMapping(); |
|
844 | 4 | $documents = $cursor->toArray(false); |
|
845 | 4 | foreach ($documents as $key => $obj) { |
|
846 | 4 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
847 | 1 | $collection->set($key, $obj); |
|
848 | 1 | } else { |
|
849 | 3 | $collection->add($obj); |
|
850 | } |
||
851 | 4 | } |
|
852 | 4 | } |
|
853 | |||
854 | /** |
||
855 | * @param PersistentCollectionInterface $collection |
||
856 | * |
||
857 | * @return CursorInterface |
||
858 | */ |
||
859 | 6 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
860 | { |
||
861 | 6 | $hints = $collection->getHints(); |
|
862 | 6 | $mapping = $collection->getMapping(); |
|
863 | 6 | $repositoryMethod = $mapping['repositoryMethod']; |
|
864 | 6 | $cursor = $this->dm->getRepository($mapping['targetDocument']) |
|
865 | 6 | ->$repositoryMethod($collection->getOwner()); |
|
866 | |||
867 | 6 | if ( ! $cursor instanceof CursorInterface) { |
|
868 | throw new \BadMethodCallException("Expected repository method {$repositoryMethod} to return a CursorInterface"); |
||
869 | } |
||
870 | |||
871 | 6 | if (!empty($mapping['prime'])) { |
|
872 | 2 | if (!$cursor instanceof Cursor) { |
|
873 | throw new \BadMethodCallException("Expected repository method {$repositoryMethod} to return a Cursor to allow for priming"); |
||
874 | } |
||
875 | |||
876 | 2 | $referencePrimer = new ReferencePrimer($this->dm, $this->dm->getUnitOfWork()); |
|
877 | 2 | $primers = array_combine($mapping['prime'], array_fill(0, count($mapping['prime']), true)); |
|
878 | |||
879 | 2 | $cursor->enableReferencePriming($primers, $referencePrimer); |
|
880 | 1 | } |
|
881 | |||
882 | 5 | if (isset($mapping['sort'])) { |
|
883 | 5 | $cursor->sort($mapping['sort']); |
|
884 | 5 | } |
|
885 | 5 | if (isset($mapping['limit'])) { |
|
886 | 1 | $cursor->limit($mapping['limit']); |
|
887 | 1 | } |
|
888 | 5 | if (isset($mapping['skip'])) { |
|
889 | $cursor->skip($mapping['skip']); |
||
890 | } |
||
891 | 5 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
892 | $cursor->slaveOkay(true); |
||
893 | } |
||
894 | 5 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
895 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
896 | } |
||
897 | |||
898 | 5 | return $cursor; |
|
899 | } |
||
900 | |||
901 | /** |
||
902 | * Prepare a sort or projection array by converting keys, which are PHP |
||
903 | * property names, to MongoDB field names. |
||
904 | * |
||
905 | * @param array $fields |
||
906 | * @return array |
||
907 | */ |
||
908 | 141 | public function prepareSortOrProjection(array $fields) |
|
909 | { |
||
910 | 141 | $preparedFields = array(); |
|
911 | |||
912 | 141 | foreach ($fields as $key => $value) { |
|
913 | 39 | $preparedFields[$this->prepareFieldName($key)] = $value; |
|
914 | 141 | } |
|
915 | |||
916 | 141 | return $preparedFields; |
|
917 | } |
||
918 | |||
919 | /** |
||
920 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
921 | * |
||
922 | * @param string $fieldName |
||
923 | * @return string |
||
924 | */ |
||
925 | 93 | public function prepareFieldName($fieldName) |
|
931 | |||
932 | /** |
||
933 | * Adds discriminator criteria to an already-prepared query. |
||
934 | * |
||
935 | * This method should be used once for query criteria and not be used for |
||
936 | * nested expressions. It should be called before |
||
937 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
938 | * |
||
939 | * @param array $preparedQuery |
||
940 | * @return array |
||
941 | */ |
||
942 | 524 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
943 | { |
||
944 | /* If the class has a discriminator field, which is not already in the |
||
945 | * criteria, inject it now. The field/values need no preparation. |
||
946 | */ |
||
947 | 524 | if ($this->class->hasDiscriminator() && ! isset($preparedQuery[$this->class->discriminatorField])) { |
|
948 | 29 | $discriminatorValues = $this->getClassDiscriminatorValues($this->class); |
|
949 | 29 | if (count($discriminatorValues) === 1) { |
|
950 | 21 | $preparedQuery[$this->class->discriminatorField] = $discriminatorValues[0]; |
|
951 | 21 | } else { |
|
952 | 10 | $preparedQuery[$this->class->discriminatorField] = array('$in' => $discriminatorValues); |
|
953 | } |
||
954 | 29 | } |
|
955 | |||
956 | 524 | return $preparedQuery; |
|
957 | } |
||
958 | |||
959 | /** |
||
960 | * Adds filter criteria to an already-prepared query. |
||
961 | * |
||
962 | * This method should be used once for query criteria and not be used for |
||
963 | * nested expressions. It should be called after |
||
964 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
965 | * |
||
966 | * @param array $preparedQuery |
||
967 | * @return array |
||
968 | */ |
||
969 | 525 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
970 | { |
||
971 | /* If filter criteria exists for this class, prepare it and merge |
||
972 | * over the existing query. |
||
973 | * |
||
974 | * @todo Consider recursive merging in case the filter criteria and |
||
975 | * prepared query both contain top-level $and/$or operators. |
||
976 | */ |
||
977 | 525 | if ($filterCriteria = $this->dm->getFilterCollection()->getFilterCriteria($this->class)) { |
|
978 | 18 | $preparedQuery = $this->cm->merge($preparedQuery, $this->prepareQueryOrNewObj($filterCriteria)); |
|
979 | 18 | } |
|
980 | |||
981 | 525 | return $preparedQuery; |
|
982 | } |
||
983 | |||
984 | /** |
||
985 | * Prepares the query criteria or new document object. |
||
986 | * |
||
987 | * PHP field names and types will be converted to those used by MongoDB. |
||
988 | * |
||
989 | * @param array $query |
||
990 | * @param bool $isNewObj |
||
991 | * @return array |
||
992 | */ |
||
993 | 555 | public function prepareQueryOrNewObj(array $query, $isNewObj = false) |
|
994 | { |
||
995 | 555 | $preparedQuery = array(); |
|
996 | |||
997 | 555 | foreach ($query as $key => $value) { |
|
998 | // Recursively prepare logical query clauses |
||
999 | 515 | if (in_array($key, array('$and', '$or', '$nor')) && is_array($value)) { |
|
1000 | 20 | foreach ($value as $k2 => $v2) { |
|
1001 | 20 | $preparedQuery[$key][$k2] = $this->prepareQueryOrNewObj($v2, $isNewObj); |
|
1002 | 20 | } |
|
1003 | 20 | continue; |
|
1004 | } |
||
1005 | |||
1006 | 515 | if (isset($key[0]) && $key[0] === '$' && is_array($value)) { |
|
1007 | 26 | $preparedQuery[$key] = $this->prepareQueryOrNewObj($value, $isNewObj); |
|
1008 | 26 | continue; |
|
1009 | } |
||
1010 | |||
1011 | 515 | $preparedQueryElements = $this->prepareQueryElement($key, $value, null, true, $isNewObj); |
|
1012 | 515 | foreach ($preparedQueryElements as list($preparedKey, $preparedValue)) { |
|
1013 | 515 | $preparedQuery[$preparedKey] = is_array($preparedValue) |
|
1014 | 515 | ? array_map('\Doctrine\ODM\MongoDB\Types\Type::convertPHPToDatabaseValue', $preparedValue) |
|
1015 | 515 | : Type::convertPHPToDatabaseValue($preparedValue); |
|
1016 | 515 | } |
|
1017 | 555 | } |
|
1018 | |||
1019 | 555 | return $preparedQuery; |
|
1020 | } |
||
1021 | |||
1022 | /** |
||
1023 | * Prepares a query value and converts the PHP value to the database value |
||
1024 | * if it is an identifier. |
||
1025 | * |
||
1026 | * It also handles converting $fieldName to the database name if they are different. |
||
1027 | * |
||
1028 | * @param string $fieldName |
||
1029 | * @param mixed $value |
||
1030 | * @param ClassMetadata $class Defaults to $this->class |
||
1031 | * @param bool $prepareValue Whether or not to prepare the value |
||
1032 | * @param bool $inNewObj Whether or not newObj is being prepared |
||
1033 | * @return array An array of tuples containing prepared field names and values |
||
1034 | */ |
||
1035 | 547 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true, $inNewObj = false) |
|
1036 | { |
||
1037 | 547 | $class = isset($class) ? $class : $this->class; |
|
1038 | |||
1039 | // @todo Consider inlining calls to ClassMetadataInfo methods |
||
1040 | |||
1041 | // Process all non-identifier fields by translating field names |
||
1042 | 547 | if ($class->hasField($fieldName) && ! $class->isIdentifier($fieldName)) { |
|
1043 | 258 | $mapping = $class->fieldMappings[$fieldName]; |
|
1044 | 258 | $fieldName = $mapping['name']; |
|
1045 | |||
1046 | 258 | if ( ! $prepareValue) { |
|
1047 | 68 | return [[$fieldName, $value]]; |
|
1048 | } |
||
1049 | |||
1050 | // Prepare mapped, embedded objects |
||
1051 | 213 | if ( ! empty($mapping['embedded']) && is_object($value) && |
|
1052 | 213 | ! $this->dm->getMetadataFactory()->isTransient(get_class($value))) { |
|
1053 | 3 | return [[$fieldName, $this->pb->prepareEmbeddedDocumentValue($mapping, $value)]]; |
|
1054 | } |
||
1055 | |||
1056 | 211 | if (! empty($mapping['reference']) && is_object($value) && ! ($value instanceof \MongoId)) { |
|
1057 | try { |
||
1058 | 13 | return $this->prepareDbRefElement($fieldName, $value, $mapping, $inNewObj); |
|
1059 | 1 | } catch (MappingException $e) { |
|
1060 | // do nothing in case passed object is not mapped document |
||
1061 | } |
||
1062 | 1 | } |
|
1063 | |||
1064 | // No further preparation unless we're dealing with a simple reference |
||
1065 | // We can't have expressions in empty() with PHP < 5.5, so store it in a variable |
||
1066 | 199 | $arrayValue = (array) $value; |
|
1067 | 199 | if (empty($mapping['reference']) || $mapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID || empty($arrayValue)) { |
|
1068 | 122 | return [[$fieldName, $value]]; |
|
1069 | } |
||
1070 | |||
1071 | // Additional preparation for one or more simple reference values |
||
1072 | 105 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
1073 | |||
1074 | 105 | if ( ! is_array($value)) { |
|
1075 | 101 | return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; |
|
1076 | } |
||
1077 | |||
1078 | // Objects without operators or with DBRef fields can be converted immediately |
||
1079 | 6 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
1080 | 3 | return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; |
|
1081 | } |
||
1082 | |||
1083 | 6 | return [[$fieldName, $this->prepareQueryExpression($value, $targetClass)]]; |
|
1084 | } |
||
1085 | |||
1086 | // Process identifier fields |
||
1087 | 406 | if (($class->hasField($fieldName) && $class->isIdentifier($fieldName)) || $fieldName === '_id') { |
|
1088 | 337 | $fieldName = '_id'; |
|
1089 | |||
1090 | 337 | if ( ! $prepareValue) { |
|
1091 | 20 | return [[$fieldName, $value]]; |
|
1092 | } |
||
1093 | |||
1094 | 320 | if ( ! is_array($value)) { |
|
1095 | 297 | return [[$fieldName, $class->getDatabaseIdentifierValue($value)]]; |
|
1096 | } |
||
1097 | |||
1098 | // Objects without operators or with DBRef fields can be converted immediately |
||
1099 | 58 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
1100 | 6 | return [[$fieldName, $class->getDatabaseIdentifierValue($value)]]; |
|
1101 | } |
||
1102 | |||
1103 | 53 | return [[$fieldName, $this->prepareQueryExpression($value, $class)]]; |
|
1104 | } |
||
1105 | |||
1106 | // No processing for unmapped, non-identifier, non-dotted field names |
||
1107 | 109 | if (strpos($fieldName, '.') === false) { |
|
1108 | 48 | return [[$fieldName, $value]]; |
|
1109 | } |
||
1110 | |||
1111 | /* Process "fieldName.objectProperty" queries (on arrays or objects). |
||
1112 | * |
||
1113 | * We can limit parsing here, since at most three segments are |
||
1114 | * significant: "fieldName.objectProperty" with an optional index or key |
||
1115 | * for collections stored as either BSON arrays or objects. |
||
1116 | */ |
||
1117 | 67 | $e = explode('.', $fieldName, 4); |
|
1118 | |||
1119 | // No further processing for unmapped fields |
||
1120 | 67 | if ( ! isset($class->fieldMappings[$e[0]])) { |
|
1121 | 4 | return [[$fieldName, $value]]; |
|
1122 | } |
||
1123 | |||
1124 | 64 | $mapping = $class->fieldMappings[$e[0]]; |
|
1125 | 64 | $e[0] = $mapping['name']; |
|
1126 | |||
1127 | // Hash and raw fields will not be prepared beyond the field name |
||
1128 | 64 | if ($mapping['type'] === Type::HASH || $mapping['type'] === Type::RAW) { |
|
1129 | 1 | $fieldName = implode('.', $e); |
|
1130 | |||
1131 | 1 | return [[$fieldName, $value]]; |
|
1132 | } |
||
1133 | |||
1134 | 63 | if ($mapping['type'] == 'many' && CollectionHelper::isHash($mapping['strategy']) |
|
1135 | 63 | && isset($e[2])) { |
|
1136 | 1 | $objectProperty = $e[2]; |
|
1137 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
1138 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
1139 | 63 | } elseif ($e[1] != '$') { |
|
1140 | 61 | $fieldName = $e[0] . '.' . $e[1]; |
|
1141 | 61 | $objectProperty = $e[1]; |
|
1142 | 61 | $objectPropertyPrefix = ''; |
|
1143 | 61 | $nextObjectProperty = implode('.', array_slice($e, 2)); |
|
1144 | 62 | } elseif (isset($e[2])) { |
|
1145 | 1 | $fieldName = $e[0] . '.' . $e[1] . '.' . $e[2]; |
|
1146 | 1 | $objectProperty = $e[2]; |
|
1147 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
1148 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
1149 | 1 | } else { |
|
1150 | 1 | $fieldName = $e[0] . '.' . $e[1]; |
|
1151 | |||
1152 | 1 | return [[$fieldName, $value]]; |
|
1153 | } |
||
1154 | |||
1155 | // No further processing for fields without a targetDocument mapping |
||
1156 | 63 | if ( ! isset($mapping['targetDocument'])) { |
|
1157 | 3 | if ($nextObjectProperty) { |
|
1158 | $fieldName .= '.'.$nextObjectProperty; |
||
1159 | } |
||
1160 | |||
1161 | 3 | return [[$fieldName, $value]]; |
|
1162 | } |
||
1163 | |||
1164 | 60 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
1165 | |||
1166 | // No further processing for unmapped targetDocument fields |
||
1167 | 60 | if ( ! $targetClass->hasField($objectProperty)) { |
|
1168 | 28 | if ($nextObjectProperty) { |
|
1169 | $fieldName .= '.'.$nextObjectProperty; |
||
1170 | } |
||
1171 | |||
1172 | 28 | return [[$fieldName, $value]]; |
|
1173 | } |
||
1174 | |||
1175 | 35 | $targetMapping = $targetClass->getFieldMapping($objectProperty); |
|
1176 | 35 | $objectPropertyIsId = $targetClass->isIdentifier($objectProperty); |
|
1177 | |||
1178 | // Prepare DBRef identifiers or the mapped field's property path |
||
1179 | 35 | $fieldName = ($objectPropertyIsId && ! empty($mapping['reference']) && $mapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) |
|
1180 | 35 | ? $e[0] . '.$id' |
|
1181 | 35 | : $e[0] . '.' . $objectPropertyPrefix . $targetMapping['name']; |
|
1182 | |||
1183 | // Process targetDocument identifier fields |
||
1184 | 35 | if ($objectPropertyIsId) { |
|
1185 | 14 | if ( ! $prepareValue) { |
|
1186 | 1 | return [[$fieldName, $value]]; |
|
1187 | } |
||
1188 | |||
1189 | 13 | if ( ! is_array($value)) { |
|
1190 | 2 | return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; |
|
1191 | } |
||
1192 | |||
1193 | // Objects without operators or with DBRef fields can be converted immediately |
||
1194 | 12 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
1195 | 3 | return [[$fieldName, $targetClass->getDatabaseIdentifierValue($value)]]; |
|
1196 | } |
||
1197 | |||
1198 | 12 | return [[$fieldName, $this->prepareQueryExpression($value, $targetClass)]]; |
|
1199 | } |
||
1200 | |||
1201 | /* The property path may include a third field segment, excluding the |
||
1202 | * collection item pointer. If present, this next object property must |
||
1203 | * be processed recursively. |
||
1204 | */ |
||
1205 | 21 | if ($nextObjectProperty) { |
|
1206 | // Respect the targetDocument's class metadata when recursing |
||
1207 | 14 | $nextTargetClass = isset($targetMapping['targetDocument']) |
|
1208 | 14 | ? $this->dm->getClassMetadata($targetMapping['targetDocument']) |
|
1209 | 14 | : null; |
|
1210 | |||
1211 | 14 | $fieldNames = $this->prepareQueryElement($nextObjectProperty, $value, $nextTargetClass, $prepareValue); |
|
1212 | |||
1213 | return array_map(function ($preparedTuple) use ($fieldName) { |
||
1214 | 14 | list($key, $value) = $preparedTuple; |
|
1215 | |||
1216 | 14 | return [$fieldName . '.' . $key, $value]; |
|
1217 | 14 | }, $fieldNames); |
|
1218 | } |
||
1219 | |||
1220 | 9 | return [[$fieldName, $value]]; |
|
1221 | } |
||
1222 | |||
1223 | /** |
||
1224 | * Prepares a query expression. |
||
1225 | * |
||
1226 | * @param array|object $expression |
||
1227 | * @param ClassMetadata $class |
||
1228 | * @return array |
||
1229 | */ |
||
1230 | 71 | private function prepareQueryExpression($expression, $class) |
|
1231 | { |
||
1232 | 71 | foreach ($expression as $k => $v) { |
|
1233 | // Ignore query operators whose arguments need no type conversion |
||
1234 | 71 | if (in_array($k, array('$exists', '$type', '$mod', '$size'))) { |
|
1235 | 12 | continue; |
|
1236 | } |
||
1237 | |||
1238 | // Process query operators whose argument arrays need type conversion |
||
1239 | 71 | if (in_array($k, array('$in', '$nin', '$all')) && is_array($v)) { |
|
1240 | 69 | foreach ($v as $k2 => $v2) { |
|
1241 | 69 | $expression[$k][$k2] = $class->getDatabaseIdentifierValue($v2); |
|
1242 | 69 | } |
|
1243 | 69 | continue; |
|
1244 | } |
||
1245 | |||
1246 | // Recursively process expressions within a $not operator |
||
1247 | 14 | if ($k === '$not' && is_array($v)) { |
|
1248 | 11 | $expression[$k] = $this->prepareQueryExpression($v, $class); |
|
1249 | 11 | continue; |
|
1250 | } |
||
1251 | |||
1252 | 14 | $expression[$k] = $class->getDatabaseIdentifierValue($v); |
|
1253 | 71 | } |
|
1254 | |||
1255 | 71 | return $expression; |
|
1256 | } |
||
1257 | |||
1258 | /** |
||
1259 | * Checks whether the value has DBRef fields. |
||
1260 | * |
||
1261 | * This method doesn't check if the the value is a complete DBRef object, |
||
1262 | * although it should return true for a DBRef. Rather, we're checking that |
||
1263 | * the value has one or more fields for a DBref. In practice, this could be |
||
1264 | * $elemMatch criteria for matching a DBRef. |
||
1265 | * |
||
1266 | * @param mixed $value |
||
1267 | * @return boolean |
||
1268 | */ |
||
1269 | 72 | private function hasDBRefFields($value) |
|
1270 | { |
||
1271 | 72 | if ( ! is_array($value) && ! is_object($value)) { |
|
1272 | return false; |
||
1273 | } |
||
1274 | |||
1275 | 72 | if (is_object($value)) { |
|
1276 | $value = get_object_vars($value); |
||
1277 | } |
||
1278 | |||
1279 | 72 | foreach ($value as $key => $_) { |
|
1280 | 72 | if ($key === '$ref' || $key === '$id' || $key === '$db') { |
|
1281 | 3 | return true; |
|
1282 | } |
||
1283 | 71 | } |
|
1284 | |||
1285 | 71 | return false; |
|
1286 | } |
||
1287 | |||
1288 | /** |
||
1289 | * Checks whether the value has query operators. |
||
1290 | * |
||
1291 | * @param mixed $value |
||
1292 | * @return boolean |
||
1293 | */ |
||
1294 | 76 | private function hasQueryOperators($value) |
|
1295 | { |
||
1296 | 76 | if ( ! is_array($value) && ! is_object($value)) { |
|
1297 | return false; |
||
1298 | } |
||
1299 | |||
1300 | 76 | if (is_object($value)) { |
|
1301 | $value = get_object_vars($value); |
||
1302 | } |
||
1303 | |||
1304 | 76 | foreach ($value as $key => $_) { |
|
1305 | 76 | if (isset($key[0]) && $key[0] === '$') { |
|
1306 | 72 | return true; |
|
1307 | } |
||
1308 | 9 | } |
|
1309 | |||
1310 | 9 | return false; |
|
1311 | } |
||
1312 | |||
1313 | /** |
||
1314 | * Gets the array of discriminator values for the given ClassMetadata |
||
1315 | * |
||
1316 | * @param ClassMetadata $metadata |
||
1317 | * @return array |
||
1318 | */ |
||
1319 | 29 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1320 | { |
||
1321 | 29 | $discriminatorValues = array($metadata->discriminatorValue); |
|
1322 | 29 | foreach ($metadata->subClasses as $className) { |
|
1323 | 8 | if ($key = array_search($className, $metadata->discriminatorMap)) { |
|
1324 | 8 | $discriminatorValues[] = $key; |
|
1325 | 8 | } |
|
1326 | 29 | } |
|
1327 | |||
1328 | // If a defaultDiscriminatorValue is set and it is among the discriminators being queries, add NULL to the list |
||
1329 | 29 | View Code Duplication | if ($metadata->defaultDiscriminatorValue && array_search($metadata->defaultDiscriminatorValue, $discriminatorValues) !== false) { |
1330 | 2 | $discriminatorValues[] = null; |
|
1331 | 2 | } |
|
1332 | |||
1333 | 29 | return $discriminatorValues; |
|
1334 | } |
||
1335 | |||
1336 | 596 | private function handleCollections($document, $options) |
|
1337 | { |
||
1338 | // Collection deletions (deletions of complete collections) |
||
1339 | 596 | foreach ($this->uow->getScheduledCollections($document) as $coll) { |
|
1340 | 107 | if ($this->uow->isCollectionScheduledForDeletion($coll)) { |
|
1341 | 31 | $this->cp->delete($coll, $options); |
|
1342 | 31 | } |
|
1343 | 596 | } |
|
1344 | // Collection updates (deleteRows, updateRows, insertRows) |
||
1345 | 596 | foreach ($this->uow->getScheduledCollections($document) as $coll) { |
|
1346 | 107 | if ($this->uow->isCollectionScheduledForUpdate($coll)) { |
|
1347 | 99 | $this->cp->update($coll, $options); |
|
1348 | 99 | } |
|
1349 | 596 | } |
|
1350 | // Take new snapshots from visited collections |
||
1351 | 596 | foreach ($this->uow->getVisitedCollections($document) as $coll) { |
|
1352 | 250 | $coll->takeSnapshot(); |
|
1353 | 596 | } |
|
1354 | 596 | } |
|
1355 | |||
1356 | /** |
||
1357 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
1358 | * Also, shard key field should be present in actual document data. |
||
1359 | * |
||
1360 | * @param object $document |
||
1361 | * @param string $shardKeyField |
||
1362 | * @param array $actualDocumentData |
||
1363 | * |
||
1364 | * @throws MongoDBException |
||
1365 | */ |
||
1366 | 3 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
1367 | { |
||
1368 | 3 | $dcs = $this->uow->getDocumentChangeSet($document); |
|
1369 | 3 | $isUpdate = $this->uow->isScheduledForUpdate($document); |
|
1370 | |||
1371 | 3 | $fieldMapping = $this->class->getFieldMappingByDbFieldName($shardKeyField); |
|
1372 | 3 | $fieldName = $fieldMapping['fieldName']; |
|
1373 | |||
1374 | 3 | if ($isUpdate && isset($dcs[$fieldName]) && $dcs[$fieldName][0] != $dcs[$fieldName][1]) { |
|
1375 | throw MongoDBException::shardKeyFieldCannotBeChanged($shardKeyField, $this->class->getName()); |
||
1376 | } |
||
1377 | |||
1378 | 3 | if (!isset($actualDocumentData[$fieldName])) { |
|
1379 | throw MongoDBException::shardKeyFieldMissing($shardKeyField, $this->class->getName()); |
||
1380 | } |
||
1381 | 3 | } |
|
1382 | |||
1383 | /** |
||
1384 | * Get shard key aware query for single document. |
||
1385 | * |
||
1386 | * @param object $document |
||
1387 | * |
||
1388 | * @return array |
||
1389 | */ |
||
1390 | 294 | private function getQueryForDocument($document) |
|
1400 | |||
1401 | /** |
||
1402 | * @param array $options |
||
1403 | * |
||
1404 | * @return array |
||
1405 | */ |
||
1406 | 597 | private function getWriteOptions(array $options = array()) |
|
1407 | { |
||
1408 | 597 | $defaultOptions = $this->dm->getConfiguration()->getDefaultCommitOptions(); |
|
1409 | 597 | $documentOptions = []; |
|
1410 | 597 | if ($this->class->hasWriteConcern()) { |
|
1411 | 9 | $documentOptions['w'] = $this->class->getWriteConcern(); |
|
1412 | 9 | } |
|
1413 | |||
1414 | 597 | return array_merge($defaultOptions, $documentOptions, $options); |
|
1415 | } |
||
1416 | |||
1417 | /** |
||
1418 | * @param string $fieldName |
||
1419 | * @param mixed $value |
||
1420 | * @param array $mapping |
||
1421 | * @param bool $inNewObj |
||
1422 | * @return array |
||
1423 | */ |
||
1424 | 13 | private function prepareDbRefElement($fieldName, $value, array $mapping, $inNewObj) |
|
1425 | { |
||
1426 | 13 | $dbRef = $this->dm->createDBRef($value, $mapping); |
|
1427 | 12 | if ($inNewObj) { |
|
1451 | } |
||
1452 |
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: