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 | 709 | public function __construct( |
|
148 | |||
149 | /** |
||
150 | * @return array |
||
151 | */ |
||
152 | public function getInserts() |
||
153 | { |
||
154 | return $this->queuedInserts; |
||
155 | } |
||
156 | |||
157 | /** |
||
158 | * @param object $document |
||
159 | * @return bool |
||
160 | */ |
||
161 | public function isQueuedForInsert($document) |
||
162 | { |
||
163 | return isset($this->queuedInserts[spl_object_hash($document)]); |
||
164 | } |
||
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 | 505 | public function addInsert($document) |
|
173 | { |
||
174 | 505 | $this->queuedInserts[spl_object_hash($document)] = $document; |
|
175 | 505 | } |
|
176 | |||
177 | /** |
||
178 | * @return array |
||
179 | */ |
||
180 | public function getUpserts() |
||
181 | { |
||
182 | return $this->queuedUpserts; |
||
183 | } |
||
184 | |||
185 | /** |
||
186 | * @param object $document |
||
187 | * @return boolean |
||
188 | */ |
||
189 | public function isQueuedForUpsert($document) |
||
190 | { |
||
191 | return isset($this->queuedUpserts[spl_object_hash($document)]); |
||
192 | } |
||
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 | 77 | public function addUpsert($document) |
|
201 | { |
||
202 | 77 | $this->queuedUpserts[spl_object_hash($document)] = $document; |
|
203 | 77 | } |
|
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() |
||
211 | { |
||
212 | return $this->class; |
||
213 | } |
||
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 | 505 | public function executeInserts(array $options = array()) |
|
226 | { |
||
227 | 505 | if ( ! $this->queuedInserts) { |
|
228 | return; |
||
229 | } |
||
230 | |||
231 | 505 | $inserts = array(); |
|
232 | 505 | foreach ($this->queuedInserts as $oid => $document) { |
|
233 | 505 | $data = $this->pb->prepareInsertData($document); |
|
234 | |||
235 | // Set the initial version for each insert |
||
236 | 504 | View Code Duplication | if ($this->class->isVersioned) { |
237 | 39 | $versionMapping = $this->class->fieldMappings[$this->class->versionField]; |
|
238 | 39 | if ($versionMapping['type'] === 'int') { |
|
239 | 37 | $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document)); |
|
240 | 37 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion); |
|
241 | 2 | } elseif ($versionMapping['type'] === 'date') { |
|
242 | 2 | $nextVersionDateTime = new \DateTime(); |
|
243 | 2 | $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp()); |
|
244 | 2 | $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime); |
|
245 | } |
||
246 | 39 | $data[$versionMapping['name']] = $nextVersion; |
|
247 | } |
||
248 | |||
249 | 504 | $inserts[$oid] = $data; |
|
250 | } |
||
251 | |||
252 | 504 | if ($inserts) { |
|
253 | try { |
||
254 | 504 | $this->collection->batchInsert($inserts, $options); |
|
255 | 7 | } catch (\MongoException $e) { |
|
256 | 7 | $this->queuedInserts = array(); |
|
257 | 7 | throw $e; |
|
258 | } |
||
259 | } |
||
260 | |||
261 | /* All collections except for ones using addToSet have already been |
||
262 | * saved. We have left these to be handled separately to avoid checking |
||
263 | * collection for uniqueness on PHP side. |
||
264 | */ |
||
265 | 504 | foreach ($this->queuedInserts as $document) { |
|
266 | 504 | $this->handleCollections($document, $options); |
|
267 | } |
||
268 | |||
269 | 504 | $this->queuedInserts = array(); |
|
270 | 504 | } |
|
271 | |||
272 | /** |
||
273 | * Executes all queued document upserts. |
||
274 | * |
||
275 | * Queued documents with an ID are upserted individually. |
||
276 | * |
||
277 | * If no upserts are queued, invoking this method is a NOOP. |
||
278 | * |
||
279 | * @param array $options Options for batchInsert() and update() driver methods |
||
280 | */ |
||
281 | 77 | public function executeUpserts(array $options = array()) |
|
298 | |||
299 | /** |
||
300 | * Executes a single upsert in {@link executeUpserts} |
||
301 | * |
||
302 | * @param object $document |
||
303 | * @param array $options |
||
304 | */ |
||
305 | 77 | private function executeUpsert($document, array $options) |
|
364 | |||
365 | /** |
||
366 | * Updates the already persisted document if it has any new changesets. |
||
367 | * |
||
368 | * @param object $document |
||
369 | * @param array $options Array of options to be used with update() |
||
370 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
371 | */ |
||
372 | 221 | public function update($document, array $options = array()) |
|
428 | |||
429 | /** |
||
430 | * Removes document from mongo |
||
431 | * |
||
432 | * @param mixed $document |
||
433 | * @param array $options Array of options to be used with remove() |
||
434 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
435 | */ |
||
436 | 29 | public function delete($document, array $options = array()) |
|
450 | |||
451 | /** |
||
452 | * Refreshes a managed document. |
||
453 | * |
||
454 | * @param string $id |
||
455 | * @param object $document The document to refresh. |
||
456 | * |
||
457 | * @deprecated The first argument is deprecated. |
||
458 | */ |
||
459 | 21 | public function refresh($id, $document) |
|
466 | |||
467 | /** |
||
468 | * Finds a document by a set of criteria. |
||
469 | * |
||
470 | * If a scalar or MongoId is provided for $criteria, it will be used to |
||
471 | * match an _id value. |
||
472 | * |
||
473 | * @param mixed $criteria Query criteria |
||
474 | * @param object $document Document to load the data into. If not specified, a new document is created. |
||
475 | * @param array $hints Hints for document creation |
||
476 | * @param integer $lockMode |
||
477 | * @param array $sort Sort array for Cursor::sort() |
||
478 | * @throws \Doctrine\ODM\MongoDB\LockException |
||
479 | * @return object|null The loaded and managed document instance or null if no document was found |
||
480 | * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? |
||
481 | */ |
||
482 | 364 | public function load($criteria, $document = null, array $hints = array(), $lockMode = 0, array $sort = null) |
|
483 | { |
||
484 | // TODO: remove this |
||
485 | 364 | if ($criteria === null || is_scalar($criteria) || $criteria instanceof \MongoId) { |
|
486 | $criteria = array('_id' => $criteria); |
||
487 | } |
||
488 | |||
489 | 364 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
490 | 364 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
491 | 364 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
492 | |||
493 | 364 | $cursor = $this->collection->find($criteria); |
|
494 | |||
495 | 364 | if (null !== $sort) { |
|
496 | 102 | $cursor->sort($this->prepareSortOrProjection($sort)); |
|
497 | } |
||
498 | |||
499 | 364 | $result = $cursor->getSingleResult(); |
|
500 | |||
501 | 364 | if ($this->class->isLockable) { |
|
502 | 1 | $lockMapping = $this->class->fieldMappings[$this->class->lockField]; |
|
503 | 1 | if (isset($result[$lockMapping['name']]) && $result[$lockMapping['name']] === LockMode::PESSIMISTIC_WRITE) { |
|
504 | 1 | throw LockException::lockFailed($result); |
|
505 | } |
||
506 | } |
||
507 | |||
508 | 363 | return $this->createDocument($result, $document, $hints); |
|
509 | } |
||
510 | |||
511 | /** |
||
512 | * Finds documents by a set of criteria. |
||
513 | * |
||
514 | * @param array $criteria Query criteria |
||
515 | * @param array $sort Sort array for Cursor::sort() |
||
516 | * @param integer|null $limit Limit for Cursor::limit() |
||
517 | * @param integer|null $skip Skip for Cursor::skip() |
||
518 | * @return Cursor |
||
519 | */ |
||
520 | 22 | public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null) |
|
521 | { |
||
522 | 22 | $criteria = $this->prepareQueryOrNewObj($criteria); |
|
523 | 22 | $criteria = $this->addDiscriminatorToPreparedQuery($criteria); |
|
524 | 22 | $criteria = $this->addFilterToPreparedQuery($criteria); |
|
525 | |||
526 | 22 | $baseCursor = $this->collection->find($criteria); |
|
527 | 22 | $cursor = $this->wrapCursor($baseCursor); |
|
528 | |||
529 | 22 | if (null !== $sort) { |
|
530 | 3 | $cursor->sort($sort); |
|
531 | } |
||
532 | |||
533 | 22 | if (null !== $limit) { |
|
534 | 2 | $cursor->limit($limit); |
|
535 | } |
||
536 | |||
537 | 22 | if (null !== $skip) { |
|
538 | 2 | $cursor->skip($skip); |
|
539 | } |
||
540 | |||
541 | 22 | return $cursor; |
|
542 | } |
||
543 | |||
544 | /** |
||
545 | * @param object $document |
||
546 | * |
||
547 | * @return array |
||
548 | * @throws MongoDBException |
||
549 | */ |
||
550 | 285 | private function getShardKeyQuery($document) |
|
570 | |||
571 | /** |
||
572 | * Wraps the supplied base cursor in the corresponding ODM class. |
||
573 | * |
||
574 | * @param CursorInterface $baseCursor |
||
575 | * @return Cursor |
||
576 | */ |
||
577 | 22 | private function wrapCursor(CursorInterface $baseCursor) |
|
578 | { |
||
579 | 22 | return new Cursor($baseCursor, $this->dm->getUnitOfWork(), $this->class); |
|
580 | } |
||
581 | |||
582 | /** |
||
583 | * Checks whether the given managed document exists in the database. |
||
584 | * |
||
585 | * @param object $document |
||
586 | * @return boolean TRUE if the document exists in the database, FALSE otherwise. |
||
587 | */ |
||
588 | 3 | public function exists($document) |
|
593 | |||
594 | /** |
||
595 | * Locks document by storing the lock mode on the mapped lock field. |
||
596 | * |
||
597 | * @param object $document |
||
598 | * @param int $lockMode |
||
599 | */ |
||
600 | 5 | public function lock($document, $lockMode) |
|
608 | |||
609 | /** |
||
610 | * Releases any lock that exists on this document. |
||
611 | * |
||
612 | * @param object $document |
||
613 | */ |
||
614 | 1 | public function unlock($document) |
|
622 | |||
623 | /** |
||
624 | * Creates or fills a single document object from an query result. |
||
625 | * |
||
626 | * @param object $result The query result. |
||
627 | * @param object $document The document object to fill, if any. |
||
628 | * @param array $hints Hints for document creation. |
||
629 | * @return object The filled and managed document object or NULL, if the query result is empty. |
||
630 | */ |
||
631 | 363 | private function createDocument($result, $document = null, array $hints = array()) |
|
645 | |||
646 | /** |
||
647 | * Loads a PersistentCollection data. Used in the initialize() method. |
||
648 | * |
||
649 | * @param PersistentCollectionInterface $collection |
||
650 | */ |
||
651 | 166 | public function loadCollection(PersistentCollectionInterface $collection) |
|
672 | |||
673 | 116 | private function loadEmbedManyCollection(PersistentCollectionInterface $collection) |
|
702 | |||
703 | 54 | private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection) |
|
775 | |||
776 | 14 | private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection) |
|
784 | |||
785 | /** |
||
786 | * @param PersistentCollectionInterface $collection |
||
787 | * |
||
788 | * @return Query |
||
789 | */ |
||
790 | 16 | public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection) |
|
826 | |||
827 | 3 | private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection) |
|
840 | |||
841 | /** |
||
842 | * @param PersistentCollectionInterface $collection |
||
843 | * |
||
844 | * @return CursorInterface |
||
845 | */ |
||
846 | 3 | public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection) |
|
876 | |||
877 | /** |
||
878 | * Prepare a sort or projection array by converting keys, which are PHP |
||
879 | * property names, to MongoDB field names. |
||
880 | * |
||
881 | * @param array $fields |
||
882 | * @return array |
||
883 | */ |
||
884 | 139 | public function prepareSortOrProjection(array $fields) |
|
894 | |||
895 | /** |
||
896 | * Prepare a mongodb field name and convert the PHP property names to MongoDB field names. |
||
897 | * |
||
898 | * @param string $fieldName |
||
899 | * @return string |
||
900 | */ |
||
901 | 85 | public function prepareFieldName($fieldName) |
|
907 | |||
908 | /** |
||
909 | * Adds discriminator criteria to an already-prepared query. |
||
910 | * |
||
911 | * This method should be used once for query criteria and not be used for |
||
912 | * nested expressions. It should be called before |
||
913 | * {@link DocumentPerister::addFilterToPreparedQuery()}. |
||
914 | * |
||
915 | * @param array $preparedQuery |
||
916 | * @return array |
||
917 | */ |
||
918 | 494 | public function addDiscriminatorToPreparedQuery(array $preparedQuery) |
|
934 | |||
935 | /** |
||
936 | * Adds filter criteria to an already-prepared query. |
||
937 | * |
||
938 | * This method should be used once for query criteria and not be used for |
||
939 | * nested expressions. It should be called after |
||
940 | * {@link DocumentPerister::addDiscriminatorToPreparedQuery()}. |
||
941 | * |
||
942 | * @param array $preparedQuery |
||
943 | * @return array |
||
944 | */ |
||
945 | 495 | public function addFilterToPreparedQuery(array $preparedQuery) |
|
959 | |||
960 | /** |
||
961 | * Prepares the query criteria or new document object. |
||
962 | * |
||
963 | * PHP field names and types will be converted to those used by MongoDB. |
||
964 | * |
||
965 | * @param array $query |
||
966 | * @return array |
||
967 | */ |
||
968 | 528 | public function prepareQueryOrNewObj(array $query) |
|
995 | |||
996 | /** |
||
997 | * Prepares a query value and converts the PHP value to the database value |
||
998 | * if it is an identifier. |
||
999 | * |
||
1000 | * It also handles converting $fieldName to the database name if they are different. |
||
1001 | * |
||
1002 | * @param string $fieldName |
||
1003 | * @param mixed $value |
||
1004 | * @param ClassMetadata $class Defaults to $this->class |
||
1005 | * @param boolean $prepareValue Whether or not to prepare the value |
||
1006 | * @return array Prepared field name and value |
||
1007 | */ |
||
1008 | 521 | private function prepareQueryElement($fieldName, $value = null, $class = null, $prepareValue = true) |
|
1191 | |||
1192 | /** |
||
1193 | * Prepares a query expression. |
||
1194 | * |
||
1195 | * @param array|object $expression |
||
1196 | * @param ClassMetadata $class |
||
1197 | * @return array |
||
1198 | */ |
||
1199 | 69 | private function prepareQueryExpression($expression, $class) |
|
1226 | |||
1227 | /** |
||
1228 | * Checks whether the value has DBRef fields. |
||
1229 | * |
||
1230 | * This method doesn't check if the the value is a complete DBRef object, |
||
1231 | * although it should return true for a DBRef. Rather, we're checking that |
||
1232 | * the value has one or more fields for a DBref. In practice, this could be |
||
1233 | * $elemMatch criteria for matching a DBRef. |
||
1234 | * |
||
1235 | * @param mixed $value |
||
1236 | * @return boolean |
||
1237 | */ |
||
1238 | 70 | private function hasDBRefFields($value) |
|
1256 | |||
1257 | /** |
||
1258 | * Checks whether the value has query operators. |
||
1259 | * |
||
1260 | * @param mixed $value |
||
1261 | * @return boolean |
||
1262 | */ |
||
1263 | 74 | private function hasQueryOperators($value) |
|
1281 | |||
1282 | /** |
||
1283 | * Gets the array of discriminator values for the given ClassMetadata |
||
1284 | * |
||
1285 | * @param ClassMetadata $metadata |
||
1286 | * @return array |
||
1287 | */ |
||
1288 | 21 | private function getClassDiscriminatorValues(ClassMetadata $metadata) |
|
1304 | |||
1305 | 569 | private function handleCollections($document, $options) |
|
1324 | |||
1325 | /** |
||
1326 | * If the document is new, ignore shard key field value, otherwise throw an exception. |
||
1327 | * Also, shard key field should be present in actual document data. |
||
1328 | * |
||
1329 | * @param object $document |
||
1330 | * @param string $shardKeyField |
||
1331 | * @param array $actualDocumentData |
||
1332 | * |
||
1333 | * @throws MongoDBException |
||
1334 | */ |
||
1335 | 9 | private function guardMissingShardKey($document, $shardKeyField, $actualDocumentData) |
|
1351 | |||
1352 | /** |
||
1353 | * Get shard key aware query for single document. |
||
1354 | * |
||
1355 | * @param object $document |
||
1356 | * |
||
1357 | * @return array |
||
1358 | */ |
||
1359 | 282 | private function getQueryForDocument($document) |
|
1369 | } |
||
1370 |
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: