Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like DocumentPersister often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DocumentPersister, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 46 | class DocumentPersister |
||
| 47 | { |
||
| 48 | /** |
||
| 49 | * The PersistenceBuilder instance. |
||
| 50 | * |
||
| 51 | * @var PersistenceBuilder |
||
| 52 | */ |
||
| 53 | private $pb; |
||
| 54 | |||
| 55 | /** |
||
| 56 | * The DocumentManager instance. |
||
| 57 | * |
||
| 58 | * @var DocumentManager |
||
| 59 | */ |
||
| 60 | private $dm; |
||
| 61 | |||
| 62 | /** |
||
| 63 | * The EventManager instance |
||
| 64 | * |
||
| 65 | * @var EventManager |
||
| 66 | */ |
||
| 67 | private $evm; |
||
| 68 | |||
| 69 | /** |
||
| 70 | * The UnitOfWork instance. |
||
| 71 | * |
||
| 72 | * @var UnitOfWork |
||
| 73 | */ |
||
| 74 | private $uow; |
||
| 75 | |||
| 76 | /** |
||
| 77 | * The ClassMetadata instance for the document type being persisted. |
||
| 78 | * |
||
| 79 | * @var ClassMetadata |
||
| 80 | */ |
||
| 81 | private $class; |
||
| 82 | |||
| 83 | /** |
||
| 84 | * The MongoCollection instance for this document. |
||
| 85 | * |
||
| 86 | * @var \MongoCollection |
||
| 87 | */ |
||
| 88 | private $collection; |
||
| 89 | |||
| 90 | /** |
||
| 91 | * Array of queued inserts for the persister to insert. |
||
| 92 | * |
||
| 93 | * @var array |
||
| 94 | */ |
||
| 95 | private $queuedInserts = array(); |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Array of queued inserts for the persister to insert. |
||
| 99 | * |
||
| 100 | * @var array |
||
| 101 | */ |
||
| 102 | private $queuedUpserts = array(); |
||
| 103 | |||
| 104 | /** |
||
| 105 | * The CriteriaMerger instance. |
||
| 106 | * |
||
| 107 | * @var CriteriaMerger |
||
| 108 | */ |
||
| 109 | private $cm; |
||
| 110 | |||
| 111 | /** |
||
| 112 | * The CollectionPersister instance. |
||
| 113 | * |
||
| 114 | * @var CollectionPersister |
||
| 115 | */ |
||
| 116 | private $cp; |
||
| 117 | |||
| 118 | /** |
||
| 119 | * Initializes this instance. |
||
| 120 | * |
||
| 121 | * @param PersistenceBuilder $pb |
||
| 122 | * @param DocumentManager $dm |
||
| 123 | * @param EventManager $evm |
||
| 124 | * @param UnitOfWork $uow |
||
| 125 | * @param HydratorFactory $hydratorFactory |
||
| 126 | * @param ClassMetadata $class |
||
| 127 | * @param CriteriaMerger $cm |
||
| 128 | */ |
||
| 129 | 729 | public function __construct( |
|
| 130 | PersistenceBuilder $pb, |
||
| 131 | DocumentManager $dm, |
||
| 132 | EventManager $evm, |
||
| 133 | UnitOfWork $uow, |
||
| 134 | HydratorFactory $hydratorFactory, |
||
| 135 | ClassMetadata $class, |
||
| 136 | CriteriaMerger $cm = null |
||
| 137 | ) { |
||
| 138 | 729 | $this->pb = $pb; |
|
| 139 | 729 | $this->dm = $dm; |
|
| 140 | 729 | $this->evm = $evm; |
|
| 141 | 729 | $this->cm = $cm ?: new CriteriaMerger(); |
|
| 142 | 729 | $this->uow = $uow; |
|
| 143 | 729 | $this->hydratorFactory = $hydratorFactory; |
|
|
|
|||
| 144 | 729 | $this->class = $class; |
|
| 145 | 729 | $this->collection = $dm->getDocumentCollection($class->name); |
|
| 146 | 729 | $this->cp = $this->uow->getCollectionPersister(); |
|
| 147 | 729 | } |
|
| 148 | |||
| 149 | /** |
||
| 150 | * @return array |
||
| 151 | */ |
||
| 152 | public function getInserts() |
||
| 156 | |||
| 157 | /** |
||
| 158 | * @param object $document |
||
| 159 | * @return bool |
||
| 160 | */ |
||
| 161 | public function isQueuedForInsert($document) |
||
| 165 | |||
| 166 | /** |
||
| 167 | * Adds a document to the queued insertions. |
||
| 168 | * The document remains queued until {@link executeInserts} is invoked. |
||
| 169 | * |
||
| 170 | * @param object $document The document to queue for insertion. |
||
| 171 | */ |
||
| 172 | 513 | public function addInsert($document) |
|
| 176 | |||
| 177 | /** |
||
| 178 | * @return array |
||
| 179 | */ |
||
| 180 | public function getUpserts() |
||
| 184 | |||
| 185 | /** |
||
| 186 | * @param object $document |
||
| 187 | * @return boolean |
||
| 188 | */ |
||
| 189 | public function isQueuedForUpsert($document) |
||
| 193 | |||
| 194 | /** |
||
| 195 | * Adds a document to the queued upserts. |
||
| 196 | * The document remains queued until {@link executeUpserts} is invoked. |
||
| 197 | * |
||
| 198 | * @param object $document The document to queue for insertion. |
||
| 199 | */ |
||
| 200 | 84 | public function addUpsert($document) |
|
| 204 | |||
| 205 | /** |
||
| 206 | * Gets the ClassMetadata instance of the document class this persister is used for. |
||
| 207 | * |
||
| 208 | * @return ClassMetadata |
||
| 209 | */ |
||
| 210 | public function getClassMetadata() |
||
| 214 | |||
| 215 | /** |
||
| 216 | * Executes all queued document insertions. |
||
| 217 | * |
||
| 218 | * Queued documents without an ID will inserted in a batch and queued |
||
| 219 | * documents with an ID will be upserted individually. |
||
| 220 | * |
||
| 221 | * If no inserts are queued, invoking this method is a NOOP. |
||
| 222 | * |
||
| 223 | * @param array $options Options for batchInsert() and update() driver methods |
||
| 224 | */ |
||
| 225 | 513 | public function executeInserts(array $options = array()) |
|
| 272 | |||
| 273 | /** |
||
| 274 | * Executes all queued document upserts. |
||
| 275 | * |
||
| 276 | * Queued documents with an ID are upserted individually. |
||
| 277 | * |
||
| 278 | * If no upserts are queued, invoking this method is a NOOP. |
||
| 279 | * |
||
| 280 | * @param array $options Options for batchInsert() and update() driver methods |
||
| 281 | */ |
||
| 282 | 84 | public function executeUpserts(array $options = array()) |
|
| 300 | |||
| 301 | /** |
||
| 302 | * Executes a single upsert in {@link executeUpserts} |
||
| 303 | * |
||
| 304 | * @param object $document |
||
| 305 | * @param array $options |
||
| 306 | */ |
||
| 307 | 84 | private function executeUpsert($document, array $options) |
|
| 308 | { |
||
| 309 | 84 | $options['upsert'] = true; |
|
| 310 | 84 | $criteria = $this->getQueryForDocument($document); |
|
| 311 | |||
| 312 | 84 | $data = $this->pb->prepareUpsertData($document); |
|
| 313 | |||
| 314 | // Set the initial version for each upsert |
||
| 315 | 84 | View Code Duplication | if ($this->class->isVersioned) { |
| 316 | 3 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
| 317 | 3 | if ($versionMapping['type'] === 'int') { |
|
| 318 | 2 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
| 319 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
| 320 | 1 | } elseif ($versionMapping['type'] === 'date') { |
|
| 321 | 1 | $nextVersionDateTime = new \DateTime(); |
|
| 322 | 1 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
| 323 | 1 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
| 324 | } |
||
| 325 | 3 | $data['$set'][$versionMapping['name']] = $nextVersion; |
|
| 326 | } |
||
| 327 | |||
| 328 | 84 | foreach (array_keys($criteria) as $field) { |
|
| 329 | 84 | unset($data['$set'][$field]); |
|
| 330 | } |
||
| 331 | |||
| 332 | // Do not send an empty $set modifier |
||
| 333 | 84 | if (empty($data['$set'])) { |
|
| 334 | 17 | unset($data['$set']); |
|
| 335 | } |
||
| 336 | |||
| 337 | /* If there are no modifiers remaining, we're upserting a document with |
||
| 338 | * an identifier as its only field. Since a document with the identifier |
||
| 339 | * may already exist, the desired behavior is "insert if not exists" and |
||
| 340 | * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set |
||
| 341 | * the identifier to the same value in our criteria. |
||
| 342 | * |
||
| 343 | * This will fail for versions before MongoDB 2.6, which require an |
||
| 344 | * empty $set modifier. The best we can do (without attempting to check |
||
| 345 | * server versions in advance) is attempt the 2.6+ behavior and retry |
||
| 346 | * after the relevant exception. |
||
| 347 | * |
||
| 348 | * See: https://jira.mongodb.org/browse/SERVER-12266 |
||
| 349 | */ |
||
| 350 | 84 | if (empty($data)) { |
|
| 351 | 17 | $retry = true; |
|
| 352 | 17 | $data = array('$set' => array('_id' => $criteria['_id'])); |
|
| 353 | } |
||
| 354 | |||
| 355 | try { |
||
| 356 | 84 | $this->collection->update($criteria, $data, $options); |
|
| 357 | 84 | return; |
|
| 358 | } catch (\MongoCursorException $e) { |
||
| 359 | if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) { |
||
| 360 | throw $e; |
||
| 361 | } |
||
| 362 | } |
||
| 363 | |||
| 364 | $this->collection->update($criteria, array('$set' => new \stdClass), $options); |
||
| 365 | } |
||
| 366 | |||
| 367 | /** |
||
| 368 | * Updates the already persisted document if it has any new changesets. |
||
| 369 | * |
||
| 370 | * @param object $document |
||
| 371 | * @param array $options Array of options to be used with update() |
||
| 372 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
| 373 | */ |
||
| 374 | 220 | public function update($document, array $options = array()) |
|
| 432 | |||
| 433 | /** |
||
| 434 | * Removes document from mongo |
||
| 435 | * |
||
| 436 | * @param mixed $document |
||
| 437 | * @param array $options Array of options to be used with remove() |
||
| 438 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
| 439 | */ |
||
| 440 | 32 | public function delete($document, array $options = array()) |
|
| 456 | |||
| 457 | /** |
||
| 458 | * Refreshes a managed document. |
||
| 459 | * |
||
| 460 | * @param string $id |
||
| 461 | * @param object $document The document to refresh. |
||
| 462 | * |
||
| 463 | * @deprecated The first argument is deprecated. |
||
| 464 | */ |
||
| 465 | 20 | public function refresh($id, $document) |
|
| 472 | |||
| 473 | /** |
||
| 474 | * Finds a document by a set of criteria. |
||
| 475 | * |
||
| 476 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
| 477 | * match an _id value. |
||
| 478 | * |
||
| 479 | * @param mixed $criteria Query criteria |
||
| 480 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
| 481 | * @param array $hints Hints for document creation |
||
| 482 | * @param integer $lockMode |
||
| 483 | * @param array $sort Sort array for Cursor::sort() |
||
| 484 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
| 485 | * @return object|null The loaded and managed document instance or null if no document was found |
||
| 486 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
| 487 | */ |
||
| 488 | 370 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
| 516 | |||
| 517 | /** |
||
| 518 | * Finds documents by a set of criteria. |
||
| 519 | * |
||
| 520 | * @param array $criteria Query criteria |
||
| 521 | * @param array $sort Sort array for Cursor::sort() |
||
| 522 | * @param integer|null $limit Limit for Cursor::limit() |
||
| 523 | * @param integer|null $skip Skip for Cursor::skip() |
||
| 524 | * @return Cursor |
||
| 525 | */ |
||
| 526 | 22 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
| 549 | |||
| 550 | /** |
||
| 551 | * @param object $document |
||
| 552 | * |
||
| 553 | * @return array |
||
| 554 | * @throws MongoDBException |
||
| 555 | */ |
||
| 556 | 292 | private function getShardKeyQuery($document) |
|
| 576 | |||
| 577 | /** |
||
| 578 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
| 579 | * |
||
| 580 | * @param CursorInterface $baseCursor |
||
| 581 | * @return Cursor |
||
| 582 | */ |
||
| 583 | 22 | private function wrapCursor(CursorInterface $baseCursor) |
|
| 587 | |||
| 588 | /** |
||
| 589 | * Checks whether the given managed document exists in the database. |
||
| 590 | * |
||
| 591 | * @param object $document |
||
| 592 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
| 593 | */ |
||
| 594 | 3 | public function exists($document) |
|
| 599 | |||
| 600 | /** |
||
| 601 | * Locks document by storing the lock mode on the mapped lock field. |
||
| 602 | * |
||
| 603 | * @param object $document |
||
| 604 | * @param int $lockMode |
||
| 605 | */ |
||
| 606 | 5 | public function lock($document, $lockMode) |
|
| 614 | |||
| 615 | /** |
||
| 616 | * Releases any lock that exists on this document. |
||
| 617 | * |
||
| 618 | * @param object $document |
||
| 619 | */ |
||
| 620 | 1 | public function unlock($document) |
|
| 628 | |||
| 629 | /** |
||
| 630 | * Creates or fills a single document object from an query result. |
||
| 631 | * |
||
| 632 | * @param object $result The query result. |
||
| 633 | * @param object $document The document object to fill, if any. |
||
| 634 | * @param array $hints Hints for document creation. |
||
| 635 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
| 636 | */ |
||
| 637 | 369 | private function createDocument($result, $document = null, array $hints = array()) |
|
| 651 | |||
| 652 | /** |
||
| 653 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
| 654 | * |
||
| 655 | * @param PersistentCollectionInterface $collection |
||
| 656 | */ |
||
| 657 | 168 | public function loadCollection(PersistentCollectionInterface $collection) |
|
| 678 | |||
| 679 | 118 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
| 708 | |||
| 709 | 54 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
| 781 | |||
| 782 | 14 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
| 790 | |||
| 791 | /** |
||
| 792 | * @param PersistentCollectionInterface $collection |
||
| 793 | * |
||
| 794 | * @return Query |
||
| 795 | */ |
||
| 796 | 16 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
| 797 | { |
||
| 798 | 16 | $hints = $collection->getHints(); |
|
| 799 | 16 | $mapping = $collection->getMapping(); |
|
| 800 | 16 | $owner = $collection->getOwner(); |
|
| 801 | 16 | $ownerClass = $this->dm->getClassMetadata(get_class($owner)); |
|
| 802 | 16 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
| 803 | 16 | $mappedByMapping = isset($targetClass->fieldMappings[$mapping['mappedBy']]) ? $targetClass->fieldMappings[$mapping['mappedBy']] : array(); |
|
| 804 | 16 | $mappedByFieldName = isset($mappedByMapping['storeAs']) && $mappedByMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID ? $mapping['mappedBy'] : $mapping['mappedBy'] . '.$id'; |
|
| 805 | 16 | $criteria = $this->cm->merge( |
|
| 806 | 16 | array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), |
|
| 807 | 16 | $this->dm->getFilterCollection()->getFilterCriteria($targetClass), |
|
| 808 | 16 | isset($mapping['criteria']) ? $mapping['criteria'] : array() |
|
| 809 | ); |
||
| 810 | 16 | $criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria); |
|
| 811 | 16 | $qb = $this->dm->createQueryBuilder($mapping['targetDocument']) |
|
| 812 | 16 | ->setQueryArray($criteria); |
|
| 813 | |||
| 814 | 16 | if (isset($mapping['sort'])) { |
|
| 815 | 16 | $qb->sort($mapping['sort']); |
|
| 816 | } |
||
| 817 | 16 | if (isset($mapping['limit'])) { |
|
| 818 | 1 | $qb->limit($mapping['limit']); |
|
| 819 | } |
||
| 820 | 16 | if (isset($mapping['skip'])) { |
|
| 821 | $qb->skip($mapping['skip']); |
||
| 822 | } |
||
| 823 | 16 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
| 824 | $qb->slaveOkay(true); |
||
| 825 | } |
||
| 826 | 16 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
| 827 | $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
| 828 | } |
||
| 829 | |||
| 830 | 16 | return $qb->getQuery(); |
|
| 831 | } |
||
| 832 | |||
| 833 | 3 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
| 834 | { |
||
| 835 | 3 | $cursor = $this->createReferenceManyWithRepositoryMethodCursor($collection); |
|
| 836 | 3 | $mapping = $collection->getMapping(); |
|
| 837 | 3 | $documents = $cursor->toArray(false); |
|
| 838 | 3 | foreach ($documents as $key => $obj) { |
|
| 839 | 3 | if (CollectionHelper::isHash($mapping['strategy'])) { |
|
| 840 | 1 | $collection->set($key, $obj); |
|
| 841 | } else { |
||
| 842 | 3 | $collection->add($obj); |
|
| 843 | } |
||
| 844 | } |
||
| 845 | 3 | } |
|
| 846 | |||
| 847 | /** |
||
| 848 | * @param PersistentCollectionInterface $collection |
||
| 849 | * |
||
| 850 | * @return CursorInterface |
||
| 851 | */ |
||
| 852 | 3 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
| 853 | { |
||
| 854 | 3 | $hints = $collection->getHints(); |
|
| 855 | 3 | $mapping = $collection->getMapping(); |
|
| 856 | 3 | $repositoryMethod = $mapping['repositoryMethod']; |
|
| 857 | 3 | $cursor = $this->dm->getRepository($mapping['targetDocument']) |
|
| 858 | 3 | ->$repositoryMethod($collection->getOwner()); |
|
| 859 | |||
| 860 | 3 | if ( ! $cursor instanceof CursorInterface) { |
|
| 861 | throw new \BadMethodCallException("Expected repository method {$repositoryMethod} to return a CursorInterface"); |
||
| 862 | } |
||
| 863 | |||
| 864 | 3 | if (isset($mapping['sort'])) { |
|
| 865 | 3 | $cursor->sort($mapping['sort']); |
|
| 866 | } |
||
| 867 | 3 | if (isset($mapping['limit'])) { |
|
| 868 | $cursor->limit($mapping['limit']); |
||
| 869 | } |
||
| 870 | 3 | if (isset($mapping['skip'])) { |
|
| 871 | $cursor->skip($mapping['skip']); |
||
| 872 | } |
||
| 873 | 3 | if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) { |
|
| 874 | $cursor->slaveOkay(true); |
||
| 875 | } |
||
| 876 | 3 | View Code Duplication | if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) { |
| 877 | $cursor->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); |
||
| 878 | } |
||
| 879 | |||
| 880 | 3 | return $cursor; |
|
| 881 | } |
||
| 882 | |||
| 883 | /** |
||
| 884 | * Prepare a sort or projection array by converting keys, which are PHP |
||
| 885 | * property names, to MongoDB field names. |
||
| 886 | * |
||
| 887 | * @param array $fields |
||
| 888 | * @return array |
||
| 889 | */ |
||
| 890 | 141 | public function prepareSortOrProjection(array $fields) |
|
| 900 | |||
| 901 | /** |
||
| 902 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
| 903 | * |
||
| 904 | * @param string $fieldName |
||
| 905 | * @return string |
||
| 906 | */ |
||
| 907 | 89 | public function prepareFieldName($fieldName) |
|
| 913 | |||
| 914 | /** |
||
| 915 | * Adds discriminator criteria to an already-prepared query. |
||
| 916 | * |
||
| 917 | * This method should be used once for query criteria and not be used for |
||
| 918 | * nested expressions. It should be called before |
||
| 919 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
| 920 | * |
||
| 921 | * @param array $preparedQuery |
||
| 922 | * @return array |
||
| 923 | */ |
||
| 924 | 504 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
| 940 | |||
| 941 | /** |
||
| 942 | * Adds filter criteria to an already-prepared query. |
||
| 943 | * |
||
| 944 | * This method should be used once for query criteria and not be used for |
||
| 945 | * nested expressions. It should be called after |
||
| 946 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
| 947 | * |
||
| 948 | * @param array $preparedQuery |
||
| 949 | * @return array |
||
| 950 | */ |
||
| 951 | 505 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
| 965 | |||
| 966 | /** |
||
| 967 | * Prepares the query criteria or new document object. |
||
| 968 | * |
||
| 969 | * PHP field names and types will be converted to those used by MongoDB. |
||
| 970 | * |
||
| 971 | * @param array $query |
||
| 972 | * @return array |
||
| 973 | */ |
||
| 974 | 538 | public function prepareQueryOrNewObj(array $query) |
|
| 1001 | |||
| 1002 | /** |
||
| 1003 | * Prepares a query value and converts the PHP value to the database value |
||
| 1004 | * if it is an identifier. |
||
| 1005 | * |
||
| 1006 | * It also handles converting $fieldName to the database name if they are different. |
||
| 1007 | * |
||
| 1008 | * @param string $fieldName |
||
| 1009 | * @param mixed $value |
||
| 1010 | * @param ClassMetadata $class Defaults to $this->class |
||
| 1011 | * @param boolean $prepareValue Whether or not to prepare the value |
||
| 1012 | * @return array Prepared field name and value |
||
| 1013 | */ |
||
| 1014 | 531 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true) |
|
| 1015 | { |
||
| 1016 | 531 | $class = isset($class) ? $class : $this->class; |
|
| 1017 | |||
| 1018 | // @todo Consider inlining calls to ClassMetadataInfo methods |
||
| 1019 | |||
| 1020 | // Process all non-identifier fields by translating field names |
||
| 1021 | 531 | if ($class->hasField($fieldName) && ! $class->isIdentifier($fieldName)) { |
|
| 1022 | 244 | $mapping = $class->fieldMappings[$fieldName]; |
|
| 1023 | 244 | $fieldName = $mapping['name']; |
|
| 1024 | |||
| 1025 | 244 | if ( ! $prepareValue) { |
|
| 1026 | 65 | return array($fieldName, $value); |
|
| 1027 | } |
||
| 1028 | |||
| 1029 | // Prepare mapped, embedded objects |
||
| 1030 | 200 | if ( ! empty($mapping['embedded']) && is_object($value) && |
|
| 1031 | 200 | ! $this->dm->getMetadataFactory()->isTransient(get_class($value))) { |
|
| 1032 | 3 | return array($fieldName, $this->pb->prepareEmbeddedDocumentValue($mapping, $value)); |
|
| 1033 | } |
||
| 1034 | |||
| 1035 | 198 | if (! empty($mapping['reference']) && is_object($value) && ! ($value instanceof \MongoId)) { |
|
| 1036 | try { |
||
| 1037 | 5 | return array($fieldName, $this->dm->createDBRef($value, $mapping)); |
|
| 1038 | 1 | } catch (MappingException $e) { |
|
| 1039 | // do nothing in case passed object is not mapped document |
||
| 1040 | } |
||
| 1041 | } |
||
| 1042 | |||
| 1043 | // No further preparation unless we're dealing with a simple reference |
||
| 1044 | // We can't have expressions in empty() with PHP < 5.5, so store it in a variable |
||
| 1045 | 194 | $arrayValue = (array) $value; |
|
| 1046 | 194 | if (empty($mapping['reference']) || $mapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID || empty($arrayValue)) { |
|
| 1047 | 119 | return array($fieldName, $value); |
|
| 1048 | } |
||
| 1049 | |||
| 1050 | // Additional preparation for one or more simple reference values |
||
| 1051 | 103 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
| 1052 | |||
| 1053 | 103 | if ( ! is_array($value)) { |
|
| 1054 | 99 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
| 1055 | } |
||
| 1056 | |||
| 1057 | // Objects without operators or with DBRef fields can be converted immediately |
||
| 1058 | 6 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
| 1059 | 3 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
| 1060 | } |
||
| 1061 | |||
| 1062 | 6 | return array($fieldName, $this->prepareQueryExpression($value, $targetClass)); |
|
| 1063 | } |
||
| 1064 | |||
| 1065 | // Process identifier fields |
||
| 1066 | 401 | if (($class->hasField($fieldName) && $class->isIdentifier($fieldName)) || $fieldName === '_id') { |
|
| 1067 | 332 | $fieldName = '_id'; |
|
| 1068 | |||
| 1069 | 332 | if ( ! $prepareValue) { |
|
| 1070 | 19 | return array($fieldName, $value); |
|
| 1071 | } |
||
| 1072 | |||
| 1073 | 316 | if ( ! is_array($value)) { |
|
| 1074 | 293 | return array($fieldName, $class->getDatabaseIdentifierValue($value)); |
|
| 1075 | } |
||
| 1076 | |||
| 1077 | // Objects without operators or with DBRef fields can be converted immediately |
||
| 1078 | 56 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
| 1079 | 6 | return array($fieldName, $class->getDatabaseIdentifierValue($value)); |
|
| 1080 | } |
||
| 1081 | |||
| 1082 | 51 | return array($fieldName, $this->prepareQueryExpression($value, $class)); |
|
| 1083 | } |
||
| 1084 | |||
| 1085 | // No processing for unmapped, non-identifier, non-dotted field names |
||
| 1086 | 105 | if (strpos($fieldName, '.') === false) { |
|
| 1087 | 48 | return array($fieldName, $value); |
|
| 1088 | } |
||
| 1089 | |||
| 1090 | /* Process "fieldName.objectProperty" queries (on arrays or objects). |
||
| 1091 | * |
||
| 1092 | * We can limit parsing here, since at most three segments are |
||
| 1093 | * significant: "fieldName.objectProperty" with an optional index or key |
||
| 1094 | * for collections stored as either BSON arrays or objects. |
||
| 1095 | */ |
||
| 1096 | 63 | $e = explode('.', $fieldName, 4); |
|
| 1097 | |||
| 1098 | // No further processing for unmapped fields |
||
| 1099 | 63 | if ( ! isset($class->fieldMappings[$e[0]])) { |
|
| 1100 | 4 | return array($fieldName, $value); |
|
| 1101 | } |
||
| 1102 | |||
| 1103 | 60 | $mapping = $class->fieldMappings[$e[0]]; |
|
| 1104 | 60 | $e[0] = $mapping['name']; |
|
| 1105 | |||
| 1106 | // Hash and raw fields will not be prepared beyond the field name |
||
| 1107 | 60 | if ($mapping['type'] === Type::HASH || $mapping['type'] === Type::RAW) { |
|
| 1108 | 1 | $fieldName = implode('.', $e); |
|
| 1109 | |||
| 1110 | 1 | return array($fieldName, $value); |
|
| 1111 | } |
||
| 1112 | |||
| 1113 | 59 | if ($mapping['type'] == 'many' && CollectionHelper::isHash($mapping['strategy']) |
|
| 1114 | 59 | && isset($e[2])) { |
|
| 1115 | 1 | $objectProperty = $e[2]; |
|
| 1116 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
| 1117 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
| 1118 | 58 | } elseif ($e[1] != '$') { |
|
| 1119 | 57 | $fieldName = $e[0] . '.' . $e[1]; |
|
| 1120 | 57 | $objectProperty = $e[1]; |
|
| 1121 | 57 | $objectPropertyPrefix = ''; |
|
| 1122 | 57 | $nextObjectProperty = implode('.', array_slice($e, 2)); |
|
| 1123 | 1 | } elseif (isset($e[2])) { |
|
| 1124 | 1 | $fieldName = $e[0] . '.' . $e[1] . '.' . $e[2]; |
|
| 1125 | 1 | $objectProperty = $e[2]; |
|
| 1126 | 1 | $objectPropertyPrefix = $e[1] . '.'; |
|
| 1127 | 1 | $nextObjectProperty = implode('.', array_slice($e, 3)); |
|
| 1128 | } else { |
||
| 1129 | 1 | $fieldName = $e[0] . '.' . $e[1]; |
|
| 1130 | |||
| 1131 | 1 | return array($fieldName, $value); |
|
| 1132 | } |
||
| 1133 | |||
| 1134 | // No further processing for fields without a targetDocument mapping |
||
| 1135 | 59 | if ( ! isset($mapping['targetDocument'])) { |
|
| 1136 | 3 | if ($nextObjectProperty) { |
|
| 1137 | $fieldName .= '.'.$nextObjectProperty; |
||
| 1138 | } |
||
| 1139 | |||
| 1140 | 3 | return array($fieldName, $value); |
|
| 1141 | } |
||
| 1142 | |||
| 1143 | 56 | $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); |
|
| 1144 | |||
| 1145 | // No further processing for unmapped targetDocument fields |
||
| 1146 | 56 | if ( ! $targetClass->hasField($objectProperty)) { |
|
| 1147 | 24 | if ($nextObjectProperty) { |
|
| 1148 | $fieldName .= '.'.$nextObjectProperty; |
||
| 1149 | } |
||
| 1150 | |||
| 1151 | 24 | return array($fieldName, $value); |
|
| 1152 | } |
||
| 1153 | |||
| 1154 | 35 | $targetMapping = $targetClass->getFieldMapping($objectProperty); |
|
| 1155 | 35 | $objectPropertyIsId = $targetClass->isIdentifier($objectProperty); |
|
| 1156 | |||
| 1157 | // Prepare DBRef identifiers or the mapped field's property path |
||
| 1158 | 35 | $fieldName = ($objectPropertyIsId && ! empty($mapping['reference']) && $mapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) |
|
| 1159 | 13 | ? $e[0] . '.$id' |
|
| 1160 | 35 | : $e[0] . '.' . $objectPropertyPrefix . $targetMapping['name']; |
|
| 1161 | |||
| 1162 | // Process targetDocument identifier fields |
||
| 1163 | 35 | if ($objectPropertyIsId) { |
|
| 1164 | 14 | if ( ! $prepareValue) { |
|
| 1165 | 1 | return array($fieldName, $value); |
|
| 1166 | } |
||
| 1167 | |||
| 1168 | 13 | if ( ! is_array($value)) { |
|
| 1169 | 2 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
| 1170 | } |
||
| 1171 | |||
| 1172 | // Objects without operators or with DBRef fields can be converted immediately |
||
| 1173 | 12 | View Code Duplication | if ( ! $this->hasQueryOperators($value) || $this->hasDBRefFields($value)) { |
| 1174 | 3 | return array($fieldName, $targetClass->getDatabaseIdentifierValue($value)); |
|
| 1175 | } |
||
| 1176 | |||
| 1177 | 12 | return array($fieldName, $this->prepareQueryExpression($value, $targetClass)); |
|
| 1178 | } |
||
| 1179 | |||
| 1180 | /* The property path may include a third field segment, excluding the |
||
| 1181 | * collection item pointer. If present, this next object property must |
||
| 1182 | * be processed recursively. |
||
| 1183 | */ |
||
| 1184 | 21 | if ($nextObjectProperty) { |
|
| 1185 | // Respect the targetDocument's class metadata when recursing |
||
| 1186 | 14 | $nextTargetClass = isset($targetMapping['targetDocument']) |
|
| 1187 | 8 | ? $this->dm->getClassMetadata($targetMapping['targetDocument']) |
|
| 1188 | 14 | : null; |
|
| 1189 | |||
| 1190 | 14 | list($key, $value) = $this->prepareQueryElement($nextObjectProperty, $value, $nextTargetClass, $prepareValue); |
|
| 1191 | |||
| 1192 | 14 | $fieldName .= '.' . $key; |
|
| 1193 | } |
||
| 1194 | |||
| 1195 | 21 | return array($fieldName, $value); |
|
| 1196 | } |
||
| 1197 | |||
| 1198 | /** |
||
| 1199 | * Prepares a query expression. |
||
| 1200 | * |
||
| 1201 | * @param array|object $expression |
||
| 1202 | * @param ClassMetadata $class |
||
| 1203 | * @return array |
||
| 1204 | */ |
||
| 1205 | 69 | private function prepareQueryExpression($expression, $class) |
|
| 1232 | |||
| 1233 | /** |
||
| 1234 | * Checks whether the value has DBRef fields. |
||
| 1235 | * |
||
| 1236 | * This method doesn't check if the the value is a complete DBRef object, |
||
| 1237 | * although it should return true for a DBRef. Rather, we're checking that |
||
| 1238 | * the value has one or more fields for a DBref. In practice, this could be |
||
| 1239 | * $elemMatch criteria for matching a DBRef. |
||
| 1240 | * |
||
| 1241 | * @param mixed $value |
||
| 1242 | * @return boolean |
||
| 1243 | */ |
||
| 1244 | 70 | private function hasDBRefFields($value) |
|
| 1262 | |||
| 1263 | /** |
||
| 1264 | * Checks whether the value has query operators. |
||
| 1265 | * |
||
| 1266 | * @param mixed $value |
||
| 1267 | * @return boolean |
||
| 1268 | */ |
||
| 1269 | 74 | private function hasQueryOperators($value) |
|
| 1287 | |||
| 1288 | /** |
||
| 1289 | * Gets the array of discriminator values for the given ClassMetadata |
||
| 1290 | * |
||
| 1291 | * @param ClassMetadata $metadata |
||
| 1292 | * @return array |
||
| 1293 | */ |
||
| 1294 | 23 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
| 1310 | |||
| 1311 | 584 | private function handleCollections($document, $options) |
|
| 1330 | |||
| 1331 | /** |
||
| 1332 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
| 1333 | * Also, shard key field should be present in actual document data. |
||
| 1334 | * |
||
| 1335 | * @param object $document |
||
| 1336 | * @param string $shardKeyField |
||
| 1337 | * @param array $actualDocumentData |
||
| 1338 | * |
||
| 1339 | * @throws MongoDBException |
||
| 1340 | */ |
||
| 1341 | 3 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
| 1342 | { |
||
| 1343 | 3 | $dcs = $this->uow->getDocumentChangeSet($document); |
|
| 1344 | 3 | $isUpdate = $this->uow->isScheduledForUpdate($document); |
|
| 1345 | |||
| 1346 | 3 | $fieldMapping = $this->class->getFieldMappingByDbFieldName($shardKeyField); |
|
| 1347 | 3 | $fieldName = $fieldMapping['fieldName']; |
|
| 1348 | |||
| 1349 | 3 | if ($isUpdate && isset($dcs[$fieldName]) && $dcs[$fieldName][0] != $dcs[$fieldName][1]) { |
|
| 1350 | throw MongoDBException::shardKeyFieldCannotBeChanged($shardKeyField, $this->class->getName()); |
||
| 1351 | } |
||
| 1352 | |||
| 1353 | 3 | if (!isset($actualDocumentData[$fieldName])) { |
|
| 1354 | throw MongoDBException::shardKeyFieldMissing($shardKeyField, $this->class->getName()); |
||
| 1355 | } |
||
| 1356 | 3 | } |
|
| 1357 | |||
| 1358 | /** |
||
| 1359 | * Get shard key aware query for single document. |
||
| 1360 | * |
||
| 1361 | * @param object $document |
||
| 1362 | * |
||
| 1363 | * @return array |
||
| 1364 | */ |
||
| 1365 | 289 | private function getQueryForDocument($document) |
|
| 1375 | |||
| 1376 | /** |
||
| 1377 | * @param array $options |
||
| 1378 | * |
||
| 1379 | * @return array |
||
| 1380 | */ |
||
| 1381 | 585 | private function getWriteOptions(array $options = array()) |
|
| 1391 | } |
||
| 1392 |
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: