Complex classes like Query 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 Query, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
44 | final class Query implements IteratorAggregate |
||
45 | { |
||
46 | public const TYPE_FIND = 1; |
||
47 | public const TYPE_FIND_AND_UPDATE = 2; |
||
48 | public const TYPE_FIND_AND_REMOVE = 3; |
||
49 | public const TYPE_INSERT = 4; |
||
50 | public const TYPE_UPDATE = 5; |
||
51 | public const TYPE_REMOVE = 6; |
||
52 | public const TYPE_DISTINCT = 9; |
||
53 | public const TYPE_COUNT = 11; |
||
54 | |||
55 | public const HINT_REFRESH = 1; |
||
56 | // 2 was used for HINT_SLAVE_OKAY, which was removed in 2.0 |
||
57 | public const HINT_READ_PREFERENCE = 3; |
||
58 | public const HINT_READ_ONLY = 5; |
||
59 | |||
60 | /** |
||
61 | * The DocumentManager instance. |
||
62 | * |
||
63 | * @var DocumentManager |
||
64 | */ |
||
65 | private $dm; |
||
66 | |||
67 | /** |
||
68 | * The ClassMetadata instance. |
||
69 | * |
||
70 | * @var ClassMetadata |
||
71 | */ |
||
72 | private $class; |
||
73 | |||
74 | /** |
||
75 | * Whether to hydrate results as document class instances. |
||
76 | * |
||
77 | * @var bool |
||
78 | */ |
||
79 | private $hydrate = true; |
||
80 | |||
81 | /** |
||
82 | * Array of primer Closure instances. |
||
83 | * |
||
84 | * @var array |
||
85 | */ |
||
86 | private $primers = []; |
||
87 | |||
88 | /** |
||
89 | * @var bool |
||
90 | */ |
||
91 | private $rewindable = true; |
||
92 | |||
93 | /** |
||
94 | * Hints for UnitOfWork behavior. |
||
95 | * |
||
96 | * @var array |
||
97 | */ |
||
98 | private $unitOfWorkHints = []; |
||
99 | |||
100 | /** |
||
101 | * The Collection instance. |
||
102 | * |
||
103 | * @var Collection |
||
104 | */ |
||
105 | protected $collection; |
||
106 | |||
107 | /** |
||
108 | * Query structure generated by the Builder class. |
||
109 | * |
||
110 | * @var array |
||
111 | */ |
||
112 | private $query; |
||
113 | |||
114 | /** @var Iterator|null */ |
||
115 | private $iterator; |
||
116 | |||
117 | /** |
||
118 | 164 | * Query options |
|
119 | * |
||
120 | 164 | * @var array |
|
121 | */ |
||
122 | 164 | private $options; |
|
123 | 164 | ||
124 | 38 | public function __construct(DocumentManager $dm, ClassMetadata $class, Collection $collection, array $query = [], array $options = [], bool $hydrate = true, bool $refresh = false, array $primers = [], bool $readOnly = false, bool $rewindable = true) |
|
125 | 26 | { |
|
126 | 23 | $primers = array_filter($primers); |
|
127 | 22 | ||
128 | 7 | switch ($query['type']) { |
|
129 | 5 | case self::TYPE_FIND: |
|
130 | 3 | case self::TYPE_FIND_AND_UPDATE: |
|
131 | 163 | case self::TYPE_FIND_AND_REMOVE: |
|
132 | case self::TYPE_INSERT: |
||
133 | case self::TYPE_UPDATE: |
||
134 | 1 | case self::TYPE_REMOVE: |
|
135 | case self::TYPE_DISTINCT: |
||
136 | case self::TYPE_COUNT: |
||
137 | 163 | break; |
|
138 | 163 | ||
139 | 163 | default: |
|
140 | 163 | throw new InvalidArgumentException('Invalid query type: ' . $query['type']); |
|
141 | 163 | } |
|
142 | 163 | ||
143 | 163 | $this->collection = $collection; |
|
144 | $this->query = $query; |
||
145 | 163 | $this->options = $options; |
|
146 | 163 | $this->dm = $dm; |
|
147 | $this->class = $class; |
||
148 | 163 | $this->hydrate = $hydrate; |
|
149 | 155 | $this->primers = $primers; |
|
150 | |||
151 | $this->setReadOnly($readOnly); |
||
152 | 8 | $this->setRefresh($refresh); |
|
153 | 8 | $this->setRewindable($rewindable); |
|
154 | |||
155 | 64 | if (! isset($query['readPreference'])) { |
|
156 | return; |
||
157 | 64 | } |
|
158 | 64 | ||
159 | $this->unitOfWorkHints[self::HINT_READ_PREFERENCE] = $query['readPreference']; |
||
160 | } |
||
161 | |||
162 | public function __clone() |
||
163 | { |
||
164 | $this->iterator = null; |
||
165 | } |
||
166 | |||
167 | 27 | /** |
|
168 | * Return an array of information about the query structure for debugging. |
||
169 | 27 | * |
|
170 | * The $name parameter may be used to return a specific key from the |
||
171 | * internal $query array property. If omitted, the entire array will be |
||
172 | * returned. |
||
173 | */ |
||
174 | public function debug(?string $name = null) |
||
175 | { |
||
176 | return $name !== null ? $this->query[$name] : $this->query; |
||
177 | } |
||
178 | |||
179 | 123 | /** |
|
180 | * Execute the query and returns the results. |
||
181 | 123 | * |
|
182 | * @return Iterator|UpdateResult|InsertOneResult|DeleteResult|array|object|int|null |
||
183 | 122 | * |
|
184 | 9 | * @throws MongoDBException |
|
185 | */ |
||
186 | public function execute() |
||
187 | 116 | { |
|
188 | $results = $this->runQuery(); |
||
189 | |||
190 | if (! $this->hydrate) { |
||
191 | return $results; |
||
192 | 116 | } |
|
193 | 116 | ||
194 | 116 | $uow = $this->dm->getUnitOfWork(); |
|
195 | 5 | ||
196 | /* If a single document is returned from a findAndModify command and it |
||
197 | 5 | * includes the identifier field, attempt hydration. |
|
198 | 1 | */ |
|
199 | if (($this->query['type'] === self::TYPE_FIND_AND_UPDATE || |
||
200 | 1 | $this->query['type'] === self::TYPE_FIND_AND_REMOVE) && |
|
201 | 1 | is_array($results) && isset($results['_id'])) { |
|
202 | 1 | $results = $uow->getOrCreateDocument($this->class->name, $results, $this->unitOfWorkHints); |
|
203 | |||
204 | if (! empty($this->primers)) { |
||
205 | $referencePrimer = new ReferencePrimer($this->dm, $uow); |
||
206 | |||
207 | 116 | foreach ($this->primers as $fieldName => $primer) { |
|
208 | $primer = is_callable($primer) ? $primer : null; |
||
209 | $referencePrimer->primeReferences($this->class, [$results], $fieldName, $this->unitOfWorkHints, $primer); |
||
210 | } |
||
211 | } |
||
212 | } |
||
213 | |||
214 | return $results; |
||
215 | } |
||
216 | |||
217 | /** |
||
218 | * Gets the ClassMetadata instance. |
||
219 | */ |
||
220 | public function getClass() : ClassMetadata |
||
221 | { |
||
222 | return $this->class; |
||
223 | } |
||
224 | |||
225 | public function getDocumentManager() : DocumentManager |
||
226 | { |
||
227 | return $this->dm; |
||
228 | } |
||
229 | |||
230 | /** |
||
231 | * Execute the query and return its result, which must be an Iterator. |
||
232 | * |
||
233 | * If the query type is not expected to return an Iterator, |
||
234 | * BadMethodCallException will be thrown before executing the query. |
||
235 | * Otherwise, the query will be executed and UnexpectedValueException will |
||
236 | * be thrown if {@link Query::execute()} does not return an Iterator. |
||
237 | 83 | * |
|
238 | * @see http://php.net/manual/en/iteratoraggregate.getiterator.php |
||
239 | 83 | * |
|
240 | 83 | * @throws BadMethodCallException If the query type would not return an Iterator. |
|
241 | 6 | * @throws UnexpectedValueException If the query did not return an Iterator. |
|
242 | 77 | * @throws MongoDBException |
|
243 | */ |
||
244 | public function getIterator() : Iterator |
||
245 | 6 | { |
|
246 | switch ($this->query['type']) { |
||
247 | case self::TYPE_FIND: |
||
248 | 77 | case self::TYPE_DISTINCT: |
|
249 | 77 | break; |
|
250 | 77 | ||
251 | default: |
||
252 | throw new BadMethodCallException('Iterator would not be returned for query type: ' . $this->query['type']); |
||
253 | 77 | } |
|
254 | |||
255 | if ($this->iterator === null) { |
||
256 | 77 | $result = $this->execute(); |
|
257 | if (! $result instanceof Iterator) { |
||
258 | throw new UnexpectedValueException('Iterator was not returned for query type: ' . $this->query['type']); |
||
259 | } |
||
260 | $this->iterator = $result; |
||
261 | } |
||
262 | 14 | ||
263 | return $this->iterator; |
||
264 | 14 | } |
|
265 | |||
266 | /** |
||
267 | * Return the query structure. |
||
268 | */ |
||
269 | public function getQuery() : array |
||
270 | { |
||
271 | return $this->query; |
||
272 | 64 | } |
|
273 | |||
274 | 64 | /** |
|
275 | 64 | * Execute the query and return the first result. |
|
276 | * |
||
277 | 64 | * @return array|object|null |
|
278 | */ |
||
279 | public function getSingleResult() |
||
280 | { |
||
281 | $clonedQuery = clone $this; |
||
282 | $clonedQuery->query['limit'] = 1; |
||
283 | |||
284 | return $clonedQuery->getIterator()->current() ?: null; |
||
|
|||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Return the query type. |
||
289 | */ |
||
290 | public function getType() : int |
||
294 | |||
295 | /** |
||
296 | * Sets whether or not to hydrate the documents to objects. |
||
297 | */ |
||
298 | public function setHydrate(bool $hydrate) : void |
||
302 | 163 | ||
303 | /** |
||
304 | 163 | * Set whether documents should be registered in UnitOfWork. If document would |
|
305 | 163 | * already be managed it will be left intact and new instance returned. |
|
306 | * |
||
307 | * This option has no effect if hydration is disabled. |
||
308 | */ |
||
309 | public function setReadOnly(bool $readOnly) : void |
||
313 | 163 | ||
314 | /** |
||
315 | 163 | * Set whether to refresh hydrated documents that are already in the |
|
316 | 163 | * identity map. |
|
317 | * |
||
318 | * This option has no effect if hydration is disabled. |
||
319 | */ |
||
320 | public function setRefresh(bool $refresh) : void |
||
321 | { |
||
322 | $this->unitOfWorkHints[self::HINT_REFRESH] = $refresh; |
||
324 | |||
325 | 11 | /** |
|
326 | * Set to enable wrapping of resulting Iterator with CachingIterator |
||
327 | */ |
||
328 | public function setRewindable(bool $rewindable = true) : void |
||
332 | 121 | ||
333 | /** |
||
334 | 121 | * Execute the query and return its results as an array. |
|
335 | 121 | * |
|
336 | * @see IteratorAggregate::toArray() |
||
337 | 85 | */ |
|
338 | 121 | public function toArray() : array |
|
342 | |||
343 | /** |
||
344 | * Returns an array containing the specified keys and their values from the |
||
345 | * query array, provided they exist and are not null. |
||
346 | */ |
||
347 | private function getQueryOptions(string ...$keys) : array |
||
356 | 107 | ||
357 | /** |
||
358 | 107 | * Decorate the cursor with caching, hydration, and priming behavior. |
|
359 | 20 | * |
|
360 | 20 | * Note: while this method could strictly take a MongoDB\Driver\Cursor, we |
|
361 | * accept Traversable for testing purposes since Cursor cannot be mocked. |
||
362 | * HydratingIterator, CachingIterator, and BaseIterator expect a Traversable |
||
363 | 107 | * so this should not have any adverse effects. |
|
364 | */ |
||
365 | private function makeIterator(Traversable $cursor) : Iterator |
||
380 | 83 | ||
381 | 83 | /** |
|
382 | 83 | * Returns an array with its keys renamed based on the translation map. |
|
383 | * |
||
384 | 83 | * @return array $rename Translation map (from => to) for renaming keys |
|
385 | */ |
||
386 | private function renameQueryOptions(array $options, array $rename) : array |
||
407 | |||
408 | 123 | /** |
|
409 | 123 | * Execute the query and return its result. |
|
410 | 107 | * |
|
411 | 107 | * The return value will vary based on the query type. Commands with results |
|
412 | * (e.g. aggregate, inline mapReduce) may return an ArrayIterator. Other |
||
413 | 107 | * commands and operations may return a status array or a boolean, depending |
|
414 | 107 | * on the driver's write concern. Queries and some mapReduce commands will |
|
415 | 107 | * return an Iterator. |
|
416 | * |
||
417 | * @return Iterator|UpdateResult|InsertOneResult|DeleteResult|array|object|int|null |
||
418 | 107 | */ |
|
419 | 24 | private function runQuery() |
|
505 | |||
506 | private function isFirstKeyUpdateOperator() : bool |
||
513 | } |
||
514 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: