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 DocumentModel 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 DocumentModel, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
33 | class DocumentModel extends SchemaModel implements ModelInterface |
||
34 | { |
||
35 | /** |
||
36 | * @var string |
||
37 | */ |
||
38 | protected $description; |
||
39 | /** |
||
40 | * @var string[] |
||
41 | */ |
||
42 | protected $fieldTitles; |
||
43 | /** |
||
44 | * @var string[] |
||
45 | */ |
||
46 | protected $fieldDescriptions; |
||
47 | /** |
||
48 | * @var string[] |
||
49 | */ |
||
50 | protected $requiredFields = array(); |
||
51 | /** |
||
52 | * @var string[] |
||
53 | */ |
||
54 | protected $searchableFields = array(); |
||
55 | /** |
||
56 | * @var DocumentRepository |
||
57 | */ |
||
58 | private $repository; |
||
59 | /** |
||
60 | * @var Visitor |
||
61 | */ |
||
62 | private $visitor; |
||
63 | /** |
||
64 | * @var array |
||
65 | */ |
||
66 | protected $notModifiableOriginRecords; |
||
67 | /** |
||
68 | * @var integer |
||
69 | */ |
||
70 | private $paginationDefaultLimit; |
||
71 | |||
72 | /** |
||
73 | * @var boolean |
||
74 | */ |
||
75 | protected $filterByAuthUser; |
||
76 | |||
77 | /** |
||
78 | * @var string |
||
79 | */ |
||
80 | protected $filterByAuthField; |
||
81 | |||
82 | /** |
||
83 | * @var RqlTranslator |
||
84 | */ |
||
85 | protected $translator; |
||
86 | |||
87 | /** |
||
88 | * @var DocumentManager |
||
89 | */ |
||
90 | protected $manager; |
||
91 | |||
92 | /** |
||
93 | * @param Visitor $visitor rql query visitor |
||
94 | * @param RqlTranslator $translator Translator for query modification |
||
95 | * @param array $notModifiableOriginRecords strings with not modifiable recordOrigin values |
||
96 | * @param integer $paginationDefaultLimit amount of data records to be returned when in pagination context |
||
97 | */ |
||
98 | 4 | public function __construct( |
|
110 | |||
111 | /** |
||
112 | * get repository instance |
||
113 | * |
||
114 | * @return DocumentRepository |
||
115 | */ |
||
116 | 2 | public function getRepository() |
|
120 | |||
121 | /** |
||
122 | * create new app model |
||
123 | * |
||
124 | * @param DocumentRepository $repository Repository of countries |
||
125 | * |
||
126 | * @return \Graviton\RestBundle\Model\DocumentModel |
||
127 | */ |
||
128 | 4 | public function setRepository(DocumentRepository $repository) |
|
135 | |||
136 | /** |
||
137 | * {@inheritDoc} |
||
138 | * |
||
139 | * @param Request $request The request object |
||
140 | * @param SecurityUser $user SecurityUser Object |
||
|
|||
141 | * @param SchemaDocument $schema Schema model used for search fields extraction |
||
142 | * |
||
143 | * @return array |
||
144 | */ |
||
145 | public function findAll(Request $request, SecurityUser $user = null, SchemaDocument $schema = null) |
||
146 | { |
||
147 | $pageNumber = $request->query->get('page', 1); |
||
148 | $numberPerPage = (int) $request->query->get('perPage', $this->getDefaultLimit()); |
||
149 | $startAt = ($pageNumber - 1) * $numberPerPage; |
||
150 | // Only 1 search text node allowed. |
||
151 | $hasSearch = false; |
||
152 | /** @var XiagQuery $queryParams */ |
||
153 | $xiagQuery = $request->attributes->get('rqlQuery'); |
||
154 | |||
155 | /** @var \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder */ |
||
156 | $queryBuilder = $this->repository |
||
157 | ->createQueryBuilder(); |
||
158 | |||
159 | // *** do we have an RQL expression, do we need to filter data? |
||
160 | if ($request->attributes->get('hasRql', false)) { |
||
161 | $innerQuery = $request->attributes->get('rqlQuery')->getQuery(); |
||
162 | $queryBuilder = $this->doRqlQuery( |
||
163 | $queryBuilder, |
||
164 | $this->translator->translateSearchQuery($xiagQuery, ['_id']) |
||
165 | ); |
||
166 | if ($this->hasCustomSearchIndex()) { |
||
167 | if ($innerQuery instanceof AbstractLogicOperatorNode) { |
||
168 | foreach ($innerQuery->getQueries() as $innerRql) { |
||
169 | View Code Duplication | if (!$hasSearch && $innerRql instanceof SearchNode) { |
|
170 | $searchString = implode(' ', $innerRql->getSearchTerms()); |
||
171 | $queryBuilder->addAnd( |
||
172 | $queryBuilder->expr()->text($searchString) |
||
173 | ); |
||
174 | $hasSearch = true; |
||
175 | } |
||
176 | } |
||
177 | View Code Duplication | } elseif ($innerQuery instanceof SearchNode) { |
|
178 | $searchString = implode(' ', $innerQuery->getSearchTerms()); |
||
179 | $queryBuilder->addAnd( |
||
180 | $queryBuilder->expr()->text($searchString) |
||
181 | ); |
||
182 | $hasSearch = true; |
||
183 | } |
||
184 | } |
||
185 | } else { |
||
186 | // @todo [lapistano]: seems the offset is missing for this query. |
||
187 | /** @var \Doctrine\ODM\MongoDB\Query\Builder $qb */ |
||
188 | $queryBuilder->find($this->repository->getDocumentName()); |
||
189 | } |
||
190 | |||
191 | /** @var LimitNode $rqlLimit */ |
||
192 | $rqlLimit = $xiagQuery instanceof XiagQuery ? $xiagQuery->getLimit() : false; |
||
193 | |||
194 | // define offset and limit |
||
195 | if (!$rqlLimit || !$rqlLimit->getOffset()) { |
||
196 | $queryBuilder->skip($startAt); |
||
197 | } else { |
||
198 | $startAt = (int) $queryParams->getLimit()->getOffset(); |
||
199 | $queryBuilder->skip($startAt); |
||
200 | } |
||
201 | |||
202 | if (!$rqlLimit || is_null($rqlLimit->getLimit())) { |
||
203 | $queryBuilder->limit($numberPerPage); |
||
204 | } else { |
||
205 | $numberPerPage = (int) $queryParams->getLimit()->getLimit(); |
||
206 | $queryBuilder->limit($numberPerPage); |
||
207 | } |
||
208 | |||
209 | // Limit can not be negative nor null. |
||
210 | if ($numberPerPage < 1) { |
||
211 | throw new RqlSyntaxErrorException('negative or null limit in rql'); |
||
212 | } |
||
213 | |||
214 | /** |
||
215 | * add a default sort on id if none was specified earlier |
||
216 | * |
||
217 | * not specifying something to sort on leads to very weird cases when fetching references |
||
218 | * If search node, sort by Score |
||
219 | * TODO Review this sorting, not 100% sure |
||
220 | */ |
||
221 | if ($hasSearch && !array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) { |
||
222 | $queryBuilder->sortMeta('score', 'textScore'); |
||
223 | } elseif (!array_key_exists('sort', $queryBuilder->getQuery()->getQuery())) { |
||
224 | $queryBuilder->sort('_id'); |
||
225 | } |
||
226 | |||
227 | // run query |
||
228 | $query = $queryBuilder->getQuery(); |
||
229 | $records = array_values($query->execute()->toArray()); |
||
230 | |||
231 | $totalCount = $query->count(); |
||
232 | $numPages = (int) ceil($totalCount / $numberPerPage); |
||
233 | $page = (int) ceil($startAt / $numberPerPage) + 1; |
||
234 | if ($numPages > 1) { |
||
235 | $request->attributes->set('paging', true); |
||
236 | $request->attributes->set('page', $page); |
||
237 | $request->attributes->set('numPages', $numPages); |
||
238 | $request->attributes->set('startAt', $startAt); |
||
239 | $request->attributes->set('perPage', $numberPerPage); |
||
240 | $request->attributes->set('totalCount', $totalCount); |
||
241 | } |
||
242 | |||
243 | return $records; |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * @param string $prefix the prefix for custom text search indexes |
||
248 | * @return bool |
||
249 | * @throws \Doctrine\ODM\MongoDB\MongoDBException |
||
250 | */ |
||
251 | private function hasCustomSearchIndex($prefix = 'search') |
||
262 | |||
263 | /** |
||
264 | * @return string the version of the MongoDB as a string |
||
265 | */ |
||
266 | private function getMongoDBVersion() |
||
277 | |||
278 | /** |
||
279 | * @param object $entity entity to insert |
||
280 | * @param bool $returnEntity true to return entity |
||
281 | * @param bool $doFlush if we should flush or not after insert |
||
282 | * |
||
283 | * @return Object|null |
||
284 | */ |
||
285 | public function insertRecord($entity, $returnEntity = true, $doFlush = true) |
||
297 | |||
298 | /** |
||
299 | * @param string $documentId id of entity to find |
||
300 | * |
||
301 | * @return Object |
||
302 | */ |
||
303 | 4 | public function find($documentId) |
|
307 | |||
308 | /** |
||
309 | * {@inheritDoc} |
||
310 | * |
||
311 | * @param string $documentId id of entity to update |
||
312 | * @param Object $entity new entity |
||
313 | * @param bool $returnEntity true to return entity |
||
314 | * |
||
315 | * @return Object|null |
||
316 | */ |
||
317 | 3 | public function updateRecord($documentId, $entity, $returnEntity = true) |
|
339 | |||
340 | /** |
||
341 | * {@inheritDoc} |
||
342 | * |
||
343 | * @param string|object $id id of entity to delete or entity instance |
||
344 | * |
||
345 | * @return null|Object |
||
346 | */ |
||
347 | public function deleteRecord($id) |
||
365 | |||
366 | /** |
||
367 | * Triggers a flush on the DocumentManager |
||
368 | * |
||
369 | * @param null $document optional document |
||
370 | * |
||
371 | * @return void |
||
372 | */ |
||
373 | public function flush($document = null) |
||
377 | |||
378 | /** |
||
379 | * A low level delete without any checks |
||
380 | * |
||
381 | * @param mixed $id record id |
||
382 | * |
||
383 | * @return void |
||
384 | */ |
||
385 | 2 | private function deleteById($id) |
|
394 | |||
395 | /** |
||
396 | * Checks in a performant way if a certain record id exists in the database |
||
397 | * |
||
398 | * @param mixed $id record id |
||
399 | * |
||
400 | * @return bool true if it exists, false otherwise |
||
401 | */ |
||
402 | 4 | public function recordExists($id) |
|
406 | |||
407 | /** |
||
408 | * Returns a set of fields from an existing resource in a performant manner. |
||
409 | * If you need to check certain fields on an object (and don't need everything), this |
||
410 | * is a better way to get what you need. |
||
411 | * If the record is not present, you will receive null. If you don't need an hydrated |
||
412 | * instance, make sure to pass false there. |
||
413 | * |
||
414 | * @param mixed $id record id |
||
415 | * @param array $fields list of fields you need. |
||
416 | * @param bool $hydrate whether to hydrate object or not |
||
417 | * |
||
418 | * @return array|null|object |
||
419 | */ |
||
420 | 4 | public function selectSingleFields($id, array $fields, $hydrate = true) |
|
434 | |||
435 | /** |
||
436 | * get classname of entity |
||
437 | * |
||
438 | * @return string|null |
||
439 | */ |
||
440 | 4 | public function getEntityClass() |
|
448 | |||
449 | /** |
||
450 | * {@inheritDoc} |
||
451 | * |
||
452 | * Currently this is being used to build the route id used for redirecting |
||
453 | * to newly made documents. It might benefit from having a different name |
||
454 | * for those purposes. |
||
455 | * |
||
456 | * We might use a convention based mapping here: |
||
457 | * Graviton\CoreBundle\Document\App -> mongodb://graviton_core |
||
458 | * Graviton\CoreBundle\Entity\Table -> mysql://graviton_core |
||
459 | * |
||
460 | * @todo implement this in a more convention based manner |
||
461 | * |
||
462 | * @return string |
||
463 | */ |
||
464 | public function getConnectionName() |
||
470 | |||
471 | /** |
||
472 | * Does the actual query using the RQL Bundle. |
||
473 | * |
||
474 | * @param Builder $queryBuilder Doctrine ODM QueryBuilder |
||
475 | * @param Query $query query from parser |
||
476 | * |
||
477 | * @return array |
||
478 | */ |
||
479 | protected function doRqlQuery($queryBuilder, Query $query) |
||
485 | |||
486 | /** |
||
487 | * Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed |
||
488 | * |
||
489 | * @param Object $record record |
||
490 | * |
||
491 | * @return void |
||
492 | */ |
||
493 | 14 | protected function checkIfOriginRecord($record) |
|
508 | |||
509 | /** |
||
510 | * Determines the configured amount fo data records to be returned in pagination context. |
||
511 | * |
||
512 | * @return int |
||
513 | */ |
||
514 | private function getDefaultLimit() |
||
522 | |||
523 | /** |
||
524 | * @param Boolean $active active |
||
525 | * @param String $field field |
||
526 | * @return void |
||
527 | */ |
||
528 | 4 | public function setFilterByAuthUser($active, $field) |
|
533 | } |
||
534 |
This check looks for
@param
annotations where the type inferred by our type inference engine differs from the declared type.It makes a suggestion as to what type it considers more descriptive.
Most often this is a case of a parameter that can be null in addition to its declared types.