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