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 |
||
45 | class DocumentPersister |
||
46 | { |
||
47 | /** |
||
48 | * The PersistenceBuilder instance. |
||
49 | * |
||
50 | * @var PersistenceBuilder |
||
51 | */ |
||
52 | private $pb; |
||
53 | |||
54 | /** |
||
55 | * The DocumentManager instance. |
||
56 | * |
||
57 | * @var DocumentManager |
||
58 | */ |
||
59 | private $dm; |
||
60 | |||
61 | /** |
||
62 | * The EventManager instance |
||
63 | * |
||
64 | * @var EventManager |
||
65 | */ |
||
66 | private $evm; |
||
67 | |||
68 | /** |
||
69 | * The UnitOfWork instance. |
||
70 | * |
||
71 | * @var UnitOfWork |
||
72 | */ |
||
73 | private $uow; |
||
74 | |||
75 | /** |
||
76 | * The ClassMetadata instance for the document type being persisted. |
||
77 | * |
||
78 | * @var ClassMetadata |
||
79 | */ |
||
80 | private $class; |
||
81 | |||
82 | /** |
||
83 | * The MongoCollection instance for this document. |
||
84 | * |
||
85 | * @var \MongoCollection |
||
86 | */ |
||
87 | private $collection; |
||
88 | |||
89 | /** |
||
90 | * Array of queued inserts for the persister to insert. |
||
91 | * |
||
92 | * @var array |
||
93 | */ |
||
94 | private $queuedInserts = array(); |
||
95 | |||
96 | /** |
||
97 | * Array of queued inserts for the persister to insert. |
||
98 | * |
||
99 | * @var array |
||
100 | */ |
||
101 | private $queuedUpserts = array(); |
||
102 | |||
103 | /** |
||
104 | * The CriteriaMerger instance. |
||
105 | * |
||
106 | * @var CriteriaMerger |
||
107 | */ |
||
108 | private $cm; |
||
109 | |||
110 | /** |
||
111 | * The CollectionPersister instance. |
||
112 | * |
||
113 | * @var CollectionPersister |
||
114 | */ |
||
115 | private $cp; |
||
116 | |||
117 | /** |
||
118 | * Initializes a new DocumentPersister instance. |
||
119 | * |
||
120 | * @param PersistenceBuilder $pb |
||
121 | * @param DocumentManager $dm |
||
122 | * @param EventManager $evm |
||
123 | * @param UnitOfWork $uow |
||
124 | * @param HydratorFactory $hydratorFactory |
||
125 | * @param ClassMetadata $class |
||
126 | */ |
||
127 | 681 | public function __construct(PersistenceBuilder $pb, DocumentManager $dm, EventManager $evm, UnitOfWork $uow, HydratorFactory $hydratorFactory, ClassMetadata $class, CriteriaMerger $cm = null) |
|
139 | |||
140 | /** |
||
141 | * @return array |
||
142 | */ |
||
143 | public function getInserts() |
||
147 | |||
148 | /** |
||
149 | * @param object $document |
||
150 | * @return bool |
||
151 | */ |
||
152 | public function isQueuedForInsert($document) |
||
156 | |||
157 | /** |
||
158 | * Adds a document to the queued insertions. |
||
159 | * The document remains queued until {@link executeInserts} is invoked. |
||
160 | * |
||
161 | * @param object $document The document to queue for insertion. |
||
162 | */ |
||
163 | 484 | public function addInsert($document) |
|
167 | |||
168 | /** |
||
169 | * @return array |
||
170 | */ |
||
171 | public function getUpserts() |
||
175 | |||
176 | /** |
||
177 | * @param object $document |
||
178 | * @return boolean |
||
179 | */ |
||
180 | public function isQueuedForUpsert($document) |
||
184 | |||
185 | /** |
||
186 | * Adds a document to the queued upserts. |
||
187 | * The document remains queued until {@link executeUpserts} is invoked. |
||
188 | * |
||
189 | * @param object $document The document to queue for insertion. |
||
190 | */ |
||
191 | 76 | public function addUpsert($document) |
|
195 | |||
196 | /** |
||
197 | * Gets the ClassMetadata instance of the document class this persister is used for. |
||
198 | * |
||
199 | * @return ClassMetadata |
||
200 | */ |
||
201 | public function getClassMetadata() |
||
205 | |||
206 | /** |
||
207 | * Executes all queued document insertions. |
||
208 | * |
||
209 | * Queued documents without an ID will inserted in a batch and queued |
||
210 | * documents with an ID will be upserted individually. |
||
211 | * |
||
212 | * If no inserts are queued, invoking this method is a NOOP. |
||
213 | * |
||
214 | * @param array $options Options for batchInsert() and update() driver methods |
||
215 | */ |
||
216 | 484 | public function executeInserts(array $options = array()) |
|
262 | |||
263 | /** |
||
264 | * Executes all queued document upserts. |
||
265 | * |
||
266 | * Queued documents with an ID are upserted individually. |
||
267 | * |
||
268 | * If no upserts are queued, invoking this method is a NOOP. |
||
269 | * |
||
270 | * @param array $options Options for batchInsert() and update() driver methods |
||
271 | */ |
||
272 | 76 | public function executeUpserts(array $options = array()) |
|
305 | |||
306 | /** |
||
307 | * Executes a single upsert in {@link executeInserts} |
||
308 | * |
||
309 | * @param array $data |
||
310 | * @param array $options |
||
311 | */ |
||
312 | 76 | private function executeUpsert(array $data, array $options) |
|
313 | { |
||
314 | 76 | $options['upsert'] = true; |
|
315 | 76 | $criteria = array('_id' => $data['$set']['_id']); |
|
316 | 76 | unset($data['$set']['_id']); |
|
317 | |||
318 | // Do not send an empty $set modifier |
||
319 | 76 | if (empty($data['$set'])) { |
|
320 | 13 | unset($data['$set']); |
|
321 | 13 | } |
|
322 | |||
323 | /* If there are no modifiers remaining, we're upserting a document with |
||
324 | * an identifier as its only field. Since a document with the identifier |
||
325 | * may already exist, the desired behavior is "insert if not exists" and |
||
326 | * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set |
||
327 | * the identifier to the same value in our criteria. |
||
328 | * |
||
329 | * This will fail for versions before MongoDB 2.6, which require an |
||
330 | * empty $set modifier. The best we can do (without attempting to check |
||
331 | * server versions in advance) is attempt the 2.6+ behavior and retry |
||
332 | * after the relevant exception. |
||
333 | * |
||
334 | * See: https://jira.mongodb.org/browse/SERVER-12266 |
||
335 | */ |
||
336 | 76 | if (empty($data)) { |
|
337 | 13 | $retry = true; |
|
338 | 13 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
339 | 13 | } |
|
340 | |||
341 | try { |
||
342 | 76 | $this->collection->update($criteria, $data, $options); |
|
343 | 76 | return; |
|
344 | } catch (\MongoCursorException $e) { |
||
345 | if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) { |
||
346 | throw $e; |
||
347 | 1 | } |
|
348 | } |
||
349 | |||
350 | $this->collection->update($criteria, array('$set' => new \stdClass), $options); |
||
351 | } |
||
352 | |||
353 | /** |
||
354 | * Updates the already persisted document if it has any new changesets. |
||
355 | * |
||
356 | * @param object $document |
||
357 | * @param array $options Array of options to be used with update() |
||
358 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
359 | */ |
||
360 | 212 | public function update($document, array $options = array()) |
|
409 | |||
410 | /** |
||
411 | * Removes document from mongo |
||
412 | * |
||
413 | * @param mixed $document |
||
414 | * @param array $options Array of options to be used with remove() |
||
415 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
416 | */ |
||
417 | 29 | public function delete($document, array $options = array()) |
|
432 | |||
433 | /** |
||
434 | * Refreshes a managed document. |
||
435 | * |
||
436 | * @param array $id The identifier of the document. |
||
437 | * @param object $document The document to refresh. |
||
438 | */ |
||
439 | 20 | public function refresh($id, $document) |
|
440 | { |
||
441 | 20 | $data = $this->collection->findOne(array('_id' => $id)); |
|
442 | 20 | $data = $this->hydratorFactory->hydrate($document, $data); |
|
443 | 20 | $this->uow->setOriginalDocumentData($document, $data); |
|
444 | 20 | } |
|
445 | |||
446 | /** |
||
447 | * Finds a document by a set of criteria. |
||
448 | * |
||
449 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
450 | * match an _id value. |
||
451 | * |
||
452 | * @param mixed $criteria Query criteria |
||
453 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
454 | * @param array $hints Hints for document creation |
||
455 | * @param integer $lockMode |
||
456 | * @param array $sort Sort array for Cursor::sort() |
||
457 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
458 | * @return object|null The loaded and managed document instance or null if no document was found |
||
459 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
460 | */ |
||
461 | 350 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
462 | { |
||
463 | // TODO: remove this |
||
464 | 350 | if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoId) { |
|
465 | 1 | $criteria = array('_id' => $criteria); |
|
466 | 1 | } |
|
467 | |||
468 | 350 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
469 | 350 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
470 | 350 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
471 | |||
472 | 350 | $cursor = $this->collection->find($criteria); |
|
473 | |||
474 | 350 | if (null !== $sort) { |
|
475 | 100 | $cursor->sort($this->prepareSortOrProjection($sort)); |
|
476 | 100 | } |
|
477 | |||
478 | 350 | $result = $cursor->getSingleResult(); |
|
479 | |||
480 | 350 | if ($this->class->isLockable) { |
|
481 | 1 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
482 | 1 | if (isset($result[$lockMapping['name']]) && $result[$lockMapping['name']] === LockMode::PESSIMISTIC_WRITE) { |
|
483 | 1 | throw LockException::lockFailed($result); |
|
484 | } |
||
485 | } |
||
486 | |||
487 | 349 | return $this->createDocument($result, $document, $hints); |
|
488 | } |
||
489 | |||
490 | /** |
||
491 | * Finds documents by a set of criteria. |
||
492 | * |
||
493 | * @param array $criteria Query criteria |
||
494 | * @param array $sort Sort array for Cursor::sort() |
||
495 | * @param integer|null $limit Limit for Cursor::limit() |
||
496 | * @param integer|null $skip Skip for Cursor::skip() |
||
497 | * @return Cursor |
||
498 | */ |
||
499 | 23 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
500 | { |
||
501 | 23 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
502 | 23 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
503 | 23 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
504 | |||
505 | 23 | $baseCursor = $this->collection->find($criteria); |
|
506 | 23 | $cursor = $this->wrapCursor($baseCursor); |
|
507 | |||
508 | 23 | if (null !== $sort) { |
|
509 | 3 | $cursor->sort($sort); |
|
510 | 3 | } |
|
511 | |||
512 | 23 | if (null !== $limit) { |
|
513 | 2 | $cursor->limit($limit); |
|
514 | 2 | } |
|
515 | |||
516 | 23 | if (null !== $skip) { |
|
517 | 2 | $cursor->skip($skip); |
|
518 | 2 | } |
|
519 | |||
520 | 23 | return $cursor; |
|
521 | } |
||
522 | |||
523 | /** |
||
524 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
525 | * |
||
526 | * @param CursorInterface $baseCursor |
||
527 | * @return Cursor |
||
528 | */ |
||
529 | 23 | private function wrapCursor(CursorInterface $baseCursor) |
|
530 | { |
||
531 | 23 | return new Cursor($baseCursor, $this->dm->getUnitOfWork(), $this->class); |
|
532 | } |
||
533 | |||
534 | /** |
||
535 | * Checks whether the given managed document exists in the database. |
||
536 | * |
||
537 | * @param object $document |
||
538 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
539 | */ |
||
540 | 3 | public function exists($document) |
|
545 | |||
546 | /** |
||
547 | * Locks document by storing the lock mode on the mapped lock field. |
||
548 | * |
||
549 | * @param object $document |
||
550 | * @param int $lockMode |
||
551 | */ |
||
552 | 5 | public function lock($document, $lockMode) |
|
560 | |||
561 | /** |
||
562 | * Releases any lock that exists on this document. |
||
563 | * |
||
564 | * @param object $document |
||
565 | */ |
||
566 | 1 | public function unlock($document) |
|
574 | |||
575 | /** |
||
576 | * Creates or fills a single document object from an query result. |
||
577 | * |
||
578 | * @param object $result The query result. |
||
579 | * @param object $document The document object to fill, if any. |
||
580 | * @param array $hints Hints for document creation. |
||
581 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
582 | */ |
||
583 | 349 | private function createDocument($result, $document = null, array $hints = array()) |
|
597 | |||
598 | /** |
||
599 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
600 | * |
||
601 | * @param PersistentCollection $collection |
||
602 | */ |
||
603 | 159 | public function loadCollection(PersistentCollection $collection) |
|
624 | |||
625 | 111 | private function loadEmbedManyCollection(PersistentCollection $collection) |
|
652 | |||
653 | 51 | private function loadReferenceManyCollectionOwningSide(PersistentCollection $collection) |
|
654 | { |
||
655 | 51 | $hints = $collection->getHints(); |
|
656 | 51 | $mapping = $collection->getMapping(); |
|
657 | 51 | $groupedIds = array(); |
|
658 | |||
659 | 51 | $sorted = isset($mapping['sort']) && $mapping['sort']; |
|
660 | |||
661 | 51 | foreach ($collection->getMongoData() as $key => $reference) { |
|
662 | 46 | if (isset($mapping['simple']) && $mapping['simple']) { |
|
663 | 4 | $className = $mapping['targetDocument']; |
|
664 | 4 | $mongoId = $reference; |
|
665 | 4 | } else { |
|
666 | 42 | $className = $this->uow->getClassNameForAssociation($mapping, $reference); |
|
667 | 42 | $mongoId = $reference['$id']; |
|
668 | } |
||
669 | 46 | $id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($mongoId); |
|
670 | |||
671 | // create a reference to the class and id |
||
672 | 46 | $reference = $this->dm->getReference($className, $id); |
|
673 | |||
674 | // no custom sort so add the references right now in the order they are embedded |
||
675 | 46 | if ( ! $sorted) { |
|
676 | 45 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
677 | 2 | $collection->set($key, $reference); |
|
678 | 2 | } else { |
|
679 | 43 | $collection->add($reference); |
|
680 | } |
||
681 | 45 | } |
|
682 | |||
683 | // only query for the referenced object if it is not already initialized or the collection is sorted |
||
684 | 46 | if (($reference instanceof Proxy && ! $reference->__isInitialized__) || $sorted) { |
|
685 | 33 | $groupedIds[$className][] = $mongoId; |
|
686 | 33 | } |
|
687 | 51 | } |
|
688 | 51 | foreach ($groupedIds as $className => $ids) { |
|
689 | 33 | $class = $this->dm->getClassMetadata($className); |
|
690 | 33 | $mongoCollection = $this->dm->getDocumentCollection($className); |
|
691 | 33 | $criteria = $this->cm->merge( |
|
692 | 33 | array('_id' => array('$in' => array_values($ids))), |
|
693 | 33 | $this->dm->getFilterCollection()->getFilterCriteria($class), |
|
694 | 33 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
695 | 33 | ); |
|
696 | 33 | $criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria); |
|
697 | 33 | $cursor = $mongoCollection->find($criteria); |
|
698 | 33 | if (isset($mapping['sort'])) { |
|
699 | 33 | $cursor->sort($mapping['sort']); |
|
700 | 33 | } |
|
701 | 33 | if (isset($mapping['limit'])) { |
|
702 | $cursor->limit($mapping['limit']); |
||
703 | } |
||
704 | 33 | if (isset($mapping['skip'])) { |
|
705 | $cursor->skip($mapping['skip']); |
||
706 | } |
||
707 | 33 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
708 | $cursor->slaveOkay(true); |
||
709 | } |
||
710 | 33 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
711 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
712 | } |
||
713 | 33 | $documents = $cursor->toArray(false); |
|
714 | 33 | foreach ($documents as $documentData) { |
|
715 | 32 | $document = $this->uow->getById($documentData['_id'], $class); |
|
716 | 32 | if ($document instanceof Proxy && ! $document->__isInitialized()) { |
|
717 | 32 | $data = $this->hydratorFactory->hydrate($document, $documentData); |
|
718 | 32 | $this->uow->setOriginalDocumentData($document, $data); |
|
719 | 32 | $document->__isInitialized__ = true; |
|
720 | 32 | } |
|
721 | 32 | if ($sorted) { |
|
722 | 1 | $collection->add($document); |
|
723 | 1 | } |
|
724 | 33 | } |
|
725 | 51 | } |
|
726 | 51 | } |
|
727 | |||
728 | 14 | private function loadReferenceManyCollectionInverseSide(PersistentCollection $collection) |
|
736 | |||
737 | /** |
||
738 | * @param PersistentCollection $collection |
||
739 | * |
||
740 | * @return Query |
||
741 | */ |
||
742 | 16 | public function createReferenceManyInverseSideQuery(PersistentCollection $collection) |
|
778 | |||
779 | 3 | private function loadReferenceManyWithRepositoryMethod(PersistentCollection $collection) |
|
780 | { |
||
781 | 3 | $cursor = $this->createReferenceManyWithRepositoryMethodCursor($collection); |
|
782 | 3 | $mapping = $collection->getMapping(); |
|
783 | 3 | $documents = $cursor->toArray(false); |
|
784 | 3 | foreach ($documents as $key => $obj) { |
|
785 | 3 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
786 | 1 | $collection->set($key, $obj); |
|
787 | 1 | } else { |
|
788 | 2 | $collection->add($obj); |
|
789 | } |
||
790 | 3 | } |
|
791 | 3 | } |
|
792 | |||
793 | /** |
||
794 | * @param PersistentCollection $collection |
||
795 | * |
||
796 | * @return CursorInterface |
||
797 | */ |
||
798 | 3 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollection $collection) |
|
799 | { |
||
800 | 3 | $hints = $collection->getHints(); |
|
801 | 3 | $mapping = $collection->getMapping(); |
|
802 | 3 | $cursor = $this->dm->getRepository($mapping['targetDocument']) |
|
803 | 3 | ->$mapping['repositoryMethod']($collection->getOwner()); |
|
804 | |||
805 | 3 | if ( ! $cursor instanceof CursorInterface) { |
|
806 | throw new \BadMethodCallException("Expected repository method {$mapping['repositoryMethod']} to return a CursorInterface"); |
||
807 | } |
||
808 | |||
809 | 3 | if (isset($mapping['sort'])) { |
|
810 | 3 | $cursor->sort($mapping['sort']); |
|
811 | 3 | } |
|
812 | 3 | if (isset($mapping['limit'])) { |
|
813 | $cursor->limit($mapping['limit']); |
||
814 | } |
||
815 | 3 | if (isset($mapping['skip'])) { |
|
816 | $cursor->skip($mapping['skip']); |
||
817 | } |
||
818 | 3 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
819 | $cursor->slaveOkay(true); |
||
820 | } |
||
821 | 3 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
822 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
823 | } |
||
824 | |||
825 | 3 | return $cursor; |
|
826 | } |
||
827 | |||
828 | /** |
||
829 | * Prepare a sort or projection array by converting keys, which are PHP |
||
830 | * property names, to MongoDB field names. |
||
831 | * |
||
832 | * @param array $fields |
||
833 | * @return array |
||
834 | */ |
||
835 | 137 | public function prepareSortOrProjection(array $fields) |
|
845 | |||
846 | /** |
||
847 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
848 | * |
||
849 | * @param string $fieldName |
||
850 | * @return string |
||
851 | */ |
||
852 | 85 | public function prepareFieldName($fieldName) |
|
858 | |||
859 | /** |
||
860 | * Adds discriminator criteria to an already-prepared query. |
||
861 | * |
||
862 | * This method should be used once for query criteria and not be used for |
||
863 | * nested expressions. It should be called before |
||
864 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
865 | * |
||
866 | * @param array $preparedQuery |
||
867 | * @return array |
||
868 | */ |
||
869 | 475 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
870 | { |
||
871 | /* If the class has a discriminator field, which is not already in the |
||
872 | * criteria, inject it now. The field/values need no preparation. |
||
873 | */ |
||
874 | 475 | if ($this->class->hasDiscriminator() && ! isset($preparedQuery[$this->class->discriminatorField])) { |
|
875 | 21 | $discriminatorValues = $this->getClassDiscriminatorValues($this->class); |
|
876 | 21 | if ((count($discriminatorValues) === 1)) { |
|
877 | 13 | $preparedQuery[$this->class->discriminatorField] = $discriminatorValues[0]; |
|
878 | 13 | } else { |
|
879 | 10 | $preparedQuery[$this->class->discriminatorField] = array('$in' => $discriminatorValues); |
|
880 | } |
||
881 | 21 | } |
|
882 | |||
883 | 475 | return $preparedQuery; |
|
884 | } |
||
885 | |||
886 | /** |
||
887 | * Adds filter criteria to an already-prepared query. |
||
888 | * |
||
889 | * This method should be used once for query criteria and not be used for |
||
890 | * nested expressions. It should be called after |
||
891 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
892 | * |
||
893 | * @param array $preparedQuery |
||
894 | * @return array |
||
895 | */ |
||
896 | 476 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
910 | |||
911 | /** |
||
912 | * Prepares the query criteria or new document object. |
||
913 | * |
||
914 | * PHP field names and types will be converted to those used by MongoDB. |
||
915 | * |
||
916 | * @param array $query |
||
917 | * @return array |
||
918 | */ |
||
919 | 509 | public function prepareQueryOrNewObj(array $query) |
|
946 | |||
947 | /** |
||
948 | * Prepares a query value and converts the PHP value to the database value |
||
949 | * if it is an identifier. |
||
950 | * |
||
951 | * It also handles converting $fieldName to the database name if they are different. |
||
952 | * |
||
953 | * @param string $fieldName |
||
954 | * @param mixed $value |
||
955 | * @param ClassMetadata $class Defaults to $this->class |
||
956 | * @param boolean $prepareValue Whether or not to prepare the value |
||
957 | * @return array Prepared field name and value |
||
958 | */ |
||
959 | 501 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true) |
|
960 | { |
||
961 | 501 | $class = isset($class) ? $class : $this->class; |
|
962 | |||
963 | // @todo Consider inlining calls to ClassMetadataInfo methods |
||
964 | |||
965 | // Process all non-identifier fields by translating field names |
||
966 | 501 | if ($class->hasField($fieldName) && ! $class->isIdentifier($fieldName)) { |
|
967 | 231 | $mapping = $class->fieldMappings[$fieldName]; |
|
968 | 231 | $fieldName = $mapping['name']; |
|
969 | |||
970 | 231 | if ( ! $prepareValue) { |
|
971 | 62 | return array($fieldName, $value); |
|
972 | } |
||
973 | |||
974 | // Prepare mapped, embedded objects |
||
975 | 189 | if ( ! empty($mapping['embedded']) && is_object($value) && |
|
976 | 189 | ! $this->dm->getMetadataFactory()->isTransient(get_class($value))) { |
|
977 | 1 | return array($fieldName, $this->pb->prepareEmbeddedDocumentValue($mapping, $value)); |
|
978 | } |
||
979 | |||
980 | // No further preparation unless we're dealing with a simple reference |
||
981 | // We can't have expressions in empty() with PHP < 5.5, so store it in a variable |
||
982 | 189 | $arrayValue = (array) $value; |
|
983 | 189 | if (empty($mapping['reference']) || empty($mapping['simple']) || empty($arrayValue)) { |
|
984 | 116 | return array($fieldName, $value); |
|
985 | } |
||
986 | |||
987 | // Additional preparation for one or more simple reference values |
||
988 | 101 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
989 | |||
990 | 101 | if ( ! is_array($value)) { |
|
991 | 97 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
992 | } |
||
993 | |||
994 | // Objects without operators or with DBRef fields can be converted immediately |
||
995 | 6 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
996 | 3 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
997 | } |
||
998 | |||
999 | 6 | return array($fieldName, $this->prepareQueryExpression($value, $targetClass)); |
|
1000 | } |
||
1001 | |||
1002 | // Process identifier fields |
||
1003 | 380 | if (($class->hasField($fieldName) && $class->isIdentifier($fieldName)) || $fieldName === '_id') { |
|
1004 | 315 | $fieldName = '_id'; |
|
1005 | |||
1006 | 315 | if ( ! $prepareValue) { |
|
1007 | 16 | return array($fieldName, $value); |
|
1008 | } |
||
1009 | |||
1010 | 301 | if ( ! is_array($value)) { |
|
1011 | 280 | return array($fieldName, $class->getDatabaseIdentifierValue($value)); |
|
1012 | } |
||
1013 | |||
1014 | // Objects without operators or with DBRef fields can be converted immediately |
||
1015 | 52 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
1016 | 6 | return array($fieldName, $class->getDatabaseIdentifierValue($value)); |
|
1017 | } |
||
1018 | |||
1019 | 47 | return array($fieldName, $this->prepareQueryExpression($value, $class)); |
|
1020 | } |
||
1021 | |||
1022 | // No processing for unmapped, non-identifier, non-dotted field names |
||
1023 | 98 | if (strpos($fieldName, '.') === false) { |
|
1024 | 42 | return array($fieldName, $value); |
|
1025 | } |
||
1026 | |||
1027 | /* Process "fieldName.objectProperty" queries (on arrays or objects). |
||
1028 | * |
||
1029 | * We can limit parsing here, since at most three segments are |
||
1030 | * significant: "fieldName.objectProperty" with an optional index or key |
||
1031 | * for collections stored as either BSON arrays or objects. |
||
1032 | */ |
||
1033 | 61 | $e = explode('.', $fieldName, 4); |
|
1034 | |||
1035 | // No further processing for unmapped fields |
||
1036 | 61 | if ( ! isset($class->fieldMappings[$e[0]])) { |
|
1037 | 3 | return array($fieldName, $value); |
|
1038 | } |
||
1039 | |||
1040 | 59 | $mapping = $class->fieldMappings[$e[0]]; |
|
1041 | 59 | $e[0] = $mapping['name']; |
|
1042 | |||
1043 | // Hash and raw fields will not be prepared beyond the field name |
||
1044 | 59 | if ($mapping['type'] === Type::HASH || $mapping['type'] === Type::RAW) { |
|
1045 | 1 | $fieldName = implode('.', $e); |
|
1046 | |||
1047 | 1 | return array($fieldName, $value); |
|
1048 | } |
||
1049 | |||
1050 | 58 | if (isset($mapping['strategy']) && CollectionHelper::isHash($mapping['strategy']) |
|
1051 | 58 | && isset($e[2])) { |
|
1052 | 1 | $objectProperty = $e[2]; |
|
1053 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
1054 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
1055 | 58 | } elseif ($e[1] != '$') { |
|
1056 | 56 | $fieldName = $e[0] . '.' . $e[1]; |
|
1057 | 56 | $objectProperty = $e[1]; |
|
1058 | 56 | $objectPropertyPrefix = ''; |
|
1059 | 56 | $nextObjectProperty = implode('.', array_slice($e, 2)); |
|
1060 | 57 | } elseif (isset($e[2])) { |
|
1061 | 1 | $fieldName = $e[0] . '.' . $e[1] . '.' . $e[2]; |
|
1062 | 1 | $objectProperty = $e[2]; |
|
1063 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
1064 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
1065 | 1 | } else { |
|
1066 | 1 | $fieldName = $e[0] . '.' . $e[1]; |
|
1067 | |||
1068 | 1 | return array($fieldName, $value); |
|
1069 | } |
||
1070 | |||
1071 | // No further processing for fields without a targetDocument mapping |
||
1072 | 58 | if ( ! isset($mapping['targetDocument'])) { |
|
1073 | 2 | if ($nextObjectProperty) { |
|
1074 | $fieldName .= '.'.$nextObjectProperty; |
||
1075 | } |
||
1076 | |||
1077 | 2 | return array($fieldName, $value); |
|
1078 | } |
||
1079 | |||
1080 | 56 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
1081 | |||
1082 | // No further processing for unmapped targetDocument fields |
||
1083 | 56 | if ( ! $targetClass->hasField($objectProperty)) { |
|
1084 | 24 | if ($nextObjectProperty) { |
|
1085 | $fieldName .= '.'.$nextObjectProperty; |
||
1086 | } |
||
1087 | |||
1088 | 24 | return array($fieldName, $value); |
|
1089 | } |
||
1090 | |||
1091 | 35 | $targetMapping = $targetClass->getFieldMapping($objectProperty); |
|
1092 | 35 | $objectPropertyIsId = $targetClass->isIdentifier($objectProperty); |
|
1093 | |||
1094 | // Prepare DBRef identifiers or the mapped field's property path |
||
1095 | 35 | $fieldName = ($objectPropertyIsId && ! empty($mapping['reference']) && empty($mapping['simple'])) |
|
1096 | 35 | ? $e[0] . '.$id' |
|
1097 | 35 | : $e[0] . '.' . $objectPropertyPrefix . $targetMapping['name']; |
|
1098 | |||
1099 | // Process targetDocument identifier fields |
||
1100 | 35 | if ($objectPropertyIsId) { |
|
1101 | 14 | if ( ! $prepareValue) { |
|
1102 | 1 | return array($fieldName, $value); |
|
1103 | } |
||
1104 | |||
1105 | 13 | if ( ! is_array($value)) { |
|
1106 | 2 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
1107 | } |
||
1108 | |||
1109 | // Objects without operators or with DBRef fields can be converted immediately |
||
1110 | 12 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
1111 | 3 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
1112 | } |
||
1113 | |||
1114 | 12 | return array($fieldName, $this->prepareQueryExpression($value, $targetClass)); |
|
1115 | } |
||
1116 | |||
1117 | /* The property path may include a third field segment, excluding the |
||
1118 | * collection item pointer. If present, this next object property must |
||
1119 | * be processed recursively. |
||
1120 | */ |
||
1121 | 21 | if ($nextObjectProperty) { |
|
1122 | // Respect the targetDocument's class metadata when recursing |
||
1123 | 14 | $nextTargetClass = isset($targetMapping['targetDocument']) |
|
1124 | 14 | ? $this->dm->getClassMetadata($targetMapping['targetDocument']) |
|
1125 | 14 | : null; |
|
1126 | |||
1127 | 14 | list($key, $value) = $this->prepareQueryElement($nextObjectProperty, $value, $nextTargetClass, $prepareValue); |
|
1128 | |||
1129 | 14 | $fieldName .= '.' . $key; |
|
1130 | 14 | } |
|
1131 | |||
1132 | 21 | return array($fieldName, $value); |
|
1133 | } |
||
1134 | |||
1135 | /** |
||
1136 | * Prepares a query expression. |
||
1137 | * |
||
1138 | * @param array|object $expression |
||
1139 | * @param ClassMetadata $class |
||
1140 | * @return array |
||
1141 | */ |
||
1142 | 65 | private function prepareQueryExpression($expression, $class) |
|
1169 | |||
1170 | /** |
||
1171 | * Checks whether the value has DBRef fields. |
||
1172 | * |
||
1173 | * This method doesn't check if the the value is a complete DBRef object, |
||
1174 | * although it should return true for a DBRef. Rather, we're checking that |
||
1175 | * the value has one or more fields for a DBref. In practice, this could be |
||
1176 | * $elemMatch criteria for matching a DBRef. |
||
1177 | * |
||
1178 | * @param mixed $value |
||
1179 | * @return boolean |
||
1180 | */ |
||
1181 | 66 | private function hasDBRefFields($value) |
|
1199 | |||
1200 | /** |
||
1201 | * Checks whether the value has query operators. |
||
1202 | * |
||
1203 | * @param mixed $value |
||
1204 | * @return boolean |
||
1205 | */ |
||
1206 | 70 | private function hasQueryOperators($value) |
|
1224 | |||
1225 | /** |
||
1226 | * Gets the array of discriminator values for the given ClassMetadata |
||
1227 | * |
||
1228 | * @param ClassMetadata $metadata |
||
1229 | * @return array |
||
1230 | */ |
||
1231 | 21 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1247 | |||
1248 | 547 | private function handleCollections($document, $options) |
|
1267 | } |
||
1268 |
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: