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 Processor 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 Processor, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
37 | class Processor |
||
38 | { |
||
39 | |||
40 | const TYPE_NAME_QUERY = '__typename'; |
||
41 | |||
42 | /** @var array */ |
||
43 | protected $data; |
||
44 | |||
45 | /** @var ResolveValidatorInterface */ |
||
46 | protected $resolveValidator; |
||
47 | |||
48 | /** @var ExecutionContext */ |
||
49 | protected $executionContext; |
||
50 | |||
51 | /** @var int */ |
||
52 | protected $maxComplexity; |
||
53 | |||
54 | 30 | public function __construct(AbstractSchema $schema) |
|
55 | { |
||
56 | /** |
||
57 | * This will be removed in 1.4 when __construct signature is changed to accept ExecutionContext |
||
58 | */ |
||
59 | 30 | if (empty($this->executionContext)) { |
|
60 | 30 | $this->executionContext = new ExecutionContext($schema); |
|
61 | 30 | $this->executionContext->setContainer(new Container()); |
|
62 | } |
||
63 | 30 | $this->resolveValidator = new ResolveValidator($this->executionContext); |
|
64 | 30 | } |
|
65 | |||
66 | 28 | public function processPayload($payload, $variables = [], $reducers = []) |
|
67 | { |
||
68 | 28 | $this->data = []; |
|
69 | |||
70 | try { |
||
71 | 28 | $this->parseAndCreateRequest($payload, $variables); |
|
72 | |||
73 | 28 | $queryType = $this->executionContext->getSchema()->getQueryType(); |
|
74 | 28 | $mutationType = $this->executionContext->getSchema()->getMutationType(); |
|
75 | |||
76 | 28 | if ($this->maxComplexity) { |
|
77 | 1 | $reducers[] = new MaxComplexityQueryVisitor($this->maxComplexity); |
|
78 | } |
||
79 | |||
80 | 28 | $this->reduceQuery($queryType, $mutationType, $reducers); |
|
81 | |||
82 | 28 | foreach ($this->executionContext->getRequest()->getOperationsInOrder() as $operation) { |
|
83 | 28 | if ($operationResult = $this->executeOperation($operation, $operation instanceof Mutation ? $mutationType : $queryType)) { |
|
84 | 28 | $this->data = array_merge($this->data, $operationResult); |
|
85 | }; |
||
86 | } |
||
87 | |||
88 | 4 | } catch (\Exception $e) { |
|
89 | 4 | $this->executionContext->addError($e); |
|
90 | } |
||
91 | |||
92 | 28 | return $this; |
|
93 | } |
||
94 | |||
95 | 28 | protected function parseAndCreateRequest($payload, $variables = []) |
|
96 | { |
||
97 | 28 | if (empty($payload)) { |
|
98 | 1 | throw new \Exception('Must provide an operation.'); |
|
99 | } |
||
100 | 28 | $parser = new Parser(); |
|
101 | |||
102 | 28 | $data = $parser->parse($payload); |
|
103 | 28 | $this->executionContext->setRequest(new Request($data, $variables)); |
|
104 | 28 | } |
|
105 | |||
106 | /** |
||
107 | * @param Query|Field $query |
||
108 | * @param AbstractObjectType $currentLevelSchema |
||
109 | * @return array|bool|mixed |
||
110 | */ |
||
111 | 28 | protected function executeOperation(Query $query, $currentLevelSchema) |
|
112 | { |
||
113 | 28 | if (!$this->resolveValidator->objectHasField($currentLevelSchema, $query)) { |
|
114 | 1 | return null; |
|
115 | } |
||
116 | |||
117 | /** @var FieldInterface $field */ |
||
118 | 28 | $operationField = $currentLevelSchema->getField($query->getName()); |
|
119 | 28 | $alias = $query->getAlias() ?: $query->getName(); |
|
120 | |||
121 | 28 | if (!$this->resolveValidator->validateArguments($operationField, $query, $this->executionContext->getRequest())) { |
|
122 | 6 | return null; |
|
123 | } |
||
124 | |||
125 | 25 | return [$alias => $this->processQueryAST($query, $operationField)]; |
|
126 | } |
||
127 | |||
128 | /** |
||
129 | * @param Query $query |
||
130 | * @param FieldInterface $field |
||
131 | * @param $contextValue |
||
132 | * @return array|mixed|null |
||
133 | */ |
||
134 | 25 | protected function processQueryAST(Query $query, FieldInterface $field, $contextValue = null) |
|
135 | { |
||
136 | 25 | if (!$this->resolveValidator->validateArguments($field, $query, $this->executionContext->getRequest())) { |
|
137 | return null; |
||
138 | } |
||
139 | |||
140 | 25 | $resolvedValue = $this->resolveFieldValue($field, $contextValue, $query->getFields(), $this->parseArgumentsValues($field, $query)); |
|
141 | |||
142 | 25 | if (!$this->resolveValidator->isValidValueForField($field, $resolvedValue)) { |
|
143 | 2 | return null; |
|
144 | } |
||
145 | |||
146 | 25 | return $this->collectValueForQueryWithType($query, $field->getType(), $resolvedValue); |
|
147 | } |
||
148 | |||
149 | /** |
||
150 | * @param Query|Mutation $query |
||
151 | * @param AbstractType $fieldType |
||
152 | * @param mixed $resolvedValue |
||
153 | * @return array|mixed |
||
154 | * @throws ResolveException |
||
155 | */ |
||
156 | 25 | protected function collectValueForQueryWithType(Query $query, AbstractType $fieldType, $resolvedValue) |
|
157 | { |
||
158 | 25 | if (is_null($resolvedValue)) { |
|
159 | 7 | return null; |
|
160 | } |
||
161 | |||
162 | 23 | $value = []; |
|
163 | |||
164 | 23 | if (!$query->hasFields()) { |
|
165 | 6 | $fieldType = $this->resolveValidator->resolveTypeIfAbstract($fieldType, $resolvedValue); |
|
166 | |||
167 | 6 | if (!TypeService::isLeafType($fieldType->getNamedType())) { |
|
168 | 1 | throw new ResolveException(sprintf('You have to specify fields for "%s"', $query->getName())); |
|
169 | } |
||
170 | 5 | if (TypeService::isScalarType($fieldType)) { |
|
171 | 5 | return $this->getOutputValue($fieldType, $resolvedValue); |
|
172 | } |
||
173 | } |
||
174 | |||
175 | 20 | if ($fieldType->getKind() == TypeMap::KIND_LIST) { |
|
176 | 9 | if (!$this->resolveValidator->hasArrayAccess($resolvedValue)) return null; |
|
177 | |||
178 | 9 | $namedType = $fieldType->getNamedType(); |
|
179 | 9 | $isAbstract = TypeService::isAbstractType($namedType); |
|
180 | 9 | $validItemStructure = false; |
|
181 | |||
182 | 9 | foreach ($resolvedValue as $resolvedValueItem) { |
|
|
|||
183 | 8 | $value[] = []; |
|
184 | 8 | $index = count($value) - 1; |
|
185 | |||
186 | 8 | if ($isAbstract) { |
|
187 | 2 | $namedType = $this->resolveValidator->resolveAbstractType($fieldType->getNamedType(), $resolvedValueItem); |
|
188 | } |
||
189 | |||
190 | 8 | if (!$validItemStructure) { |
|
191 | 8 | if (!$namedType->isValidValue($resolvedValueItem)) { |
|
192 | 1 | $this->executionContext->addError(new ResolveException(sprintf('Not valid resolve value in %s field', $query->getName()))); |
|
193 | 1 | $value[$index] = null; |
|
194 | 1 | continue; |
|
195 | } |
||
196 | 7 | $validItemStructure = true; |
|
197 | } |
||
198 | |||
199 | 9 | $value[$index] = $this->processQueryFields($query, $namedType, $resolvedValueItem, $value[$index]); |
|
200 | } |
||
201 | } else { |
||
202 | 20 | $value = $this->processQueryFields($query, $fieldType, $resolvedValue, $value); |
|
203 | } |
||
204 | |||
205 | 20 | return $value; |
|
206 | } |
||
207 | |||
208 | /** |
||
209 | * @param FieldAst $fieldAst |
||
210 | * @param FieldInterface $field |
||
211 | * |
||
212 | * @param mixed $contextValue |
||
213 | * @return array|mixed|null |
||
214 | * @throws ResolveException |
||
215 | * @throws \Exception |
||
216 | */ |
||
217 | 19 | protected function processFieldAST(FieldAst $fieldAst, FieldInterface $field, $contextValue) |
|
218 | { |
||
219 | 19 | $value = null; |
|
220 | 19 | $fieldType = $field->getType(); |
|
221 | 19 | $preResolvedValue = $this->getPreResolvedValue($contextValue, $fieldAst, $field); |
|
222 | |||
223 | 19 | if ($fieldType->getKind() == TypeMap::KIND_LIST) { |
|
224 | 1 | $listValue = []; |
|
225 | 1 | $type = $fieldType->getNamedType(); |
|
226 | |||
227 | 1 | foreach ($preResolvedValue as $resolvedValueItem) { |
|
228 | 1 | $listValue[] = $this->getOutputValue($type, $resolvedValueItem); |
|
229 | } |
||
230 | |||
231 | 1 | $value = $listValue; |
|
232 | } else { |
||
233 | 19 | $value = $this->getOutputValue($fieldType, $preResolvedValue); |
|
234 | } |
||
235 | |||
236 | 19 | return $value; |
|
237 | } |
||
238 | |||
239 | 25 | protected function createResolveInfo($field, $fields) |
|
240 | { |
||
241 | 25 | return new ResolveInfo($field, $fields, $this->executionContext); |
|
242 | } |
||
243 | |||
244 | /** |
||
245 | * @param $contextValue |
||
246 | * @param FieldAst $fieldAst |
||
247 | * @param FieldInterface $field |
||
248 | * |
||
249 | * @throws \Exception |
||
250 | * |
||
251 | * @return mixed |
||
252 | */ |
||
253 | 19 | protected function getPreResolvedValue($contextValue, FieldAst $fieldAst, FieldInterface $field) |
|
254 | { |
||
255 | 19 | if ($field->hasArguments() && !$this->resolveValidator->validateArguments($field, $fieldAst, $this->executionContext->getRequest())) { |
|
256 | throw new \Exception(sprintf('Not valid arguments for the field "%s"', $fieldAst->getName())); |
||
257 | } |
||
258 | |||
259 | 19 | return $this->resolveFieldValue($field, $contextValue, [$fieldAst], $fieldAst->getKeyValueArguments()); |
|
260 | |||
261 | } |
||
262 | |||
263 | 25 | protected function resolveFieldValue(FieldInterface $field, $contextValue, array $fields, array $args) |
|
264 | { |
||
265 | 25 | return $field->resolve($contextValue, $args, $this->createResolveInfo($field, $fields)); |
|
266 | } |
||
267 | |||
268 | /** |
||
269 | * @param $field FieldInterface |
||
270 | * @param $query Query |
||
271 | * |
||
272 | * @return array |
||
273 | */ |
||
274 | 25 | protected function parseArgumentsValues(FieldInterface $field, Query $query) |
|
275 | { |
||
276 | 25 | $args = []; |
|
277 | 25 | foreach ($query->getArguments() as $argument) { |
|
278 | 15 | if ($configArgument = $field->getArgument($argument->getName())) { |
|
279 | 15 | $args[$argument->getName()] = $configArgument->getType()->parseValue($argument->getValue()->getValue()); |
|
280 | } |
||
281 | } |
||
282 | |||
283 | 25 | return $args; |
|
284 | } |
||
285 | |||
286 | /** |
||
287 | * @param $query Query|FragmentInterface |
||
288 | * @param $queryType AbstractObjectType|TypeInterface|Field|AbstractType |
||
289 | * @param $resolvedValue mixed |
||
290 | * @param $value array |
||
291 | * |
||
292 | * @throws \Exception |
||
293 | * |
||
294 | * @return array |
||
295 | */ |
||
296 | 20 | protected function processQueryFields($query, AbstractType $queryType, $resolvedValue, $value) |
|
297 | { |
||
298 | 20 | $originalType = $queryType; |
|
299 | 20 | $queryType = $this->resolveValidator->resolveTypeIfAbstract($queryType, $resolvedValue); |
|
300 | 20 | $currentType = $queryType->getNullableType(); |
|
301 | |||
302 | |||
303 | 20 | View Code Duplication | if ($currentType->getKind() == TypeMap::KIND_SCALAR) { |
304 | 1 | if (!$query->hasFields()) { |
|
305 | 1 | return $this->getOutputValue($currentType, $resolvedValue); |
|
306 | } else { |
||
307 | 1 | $this->executionContext->addError(new ResolveException(sprintf('Fields are not found in query "%s"', $query->getName()))); |
|
308 | |||
309 | 1 | return null; |
|
310 | } |
||
311 | } |
||
312 | |||
313 | 20 | foreach ($query->getFields() as $fieldAst) { |
|
314 | |||
315 | 20 | if ($fieldAst instanceof FragmentInterface) { |
|
316 | /** @var TypedFragmentReference $fragment */ |
||
317 | 3 | $fragment = $fieldAst; |
|
318 | 3 | if ($fieldAst instanceof FragmentReference) { |
|
319 | /** @var Fragment $fragment */ |
||
320 | 2 | $fieldAstName = $fieldAst->getName(); |
|
321 | 2 | $fragment = $this->executionContext->getRequest()->getFragment($fieldAstName); |
|
322 | 2 | $this->resolveValidator->assertValidFragmentForField($fragment, $fieldAst, $originalType); |
|
323 | 1 | } elseif ($fragment->getTypeName() !== $queryType->getName()) { |
|
324 | 1 | continue; |
|
325 | } |
||
326 | |||
327 | 3 | $fragmentValue = $this->processQueryFields($fragment, $queryType, $resolvedValue, $value); |
|
328 | 3 | $value = is_array($fragmentValue) ? $fragmentValue : []; |
|
329 | } else { |
||
330 | 20 | $fieldAstName = $fieldAst->getName(); |
|
331 | 20 | $alias = $fieldAst->getAlias() ?: $fieldAstName; |
|
332 | |||
333 | 20 | if ($fieldAstName == self::TYPE_NAME_QUERY) { |
|
334 | 1 | $value[$alias] = $queryType->getName(); |
|
335 | } else { |
||
336 | 20 | $field = $currentType->getField($fieldAstName); |
|
337 | 20 | if (!$field) { |
|
338 | 3 | $this->executionContext->addError(new ResolveException(sprintf('Field "%s" is not found in type "%s"', $fieldAstName, $currentType->getName()))); |
|
339 | |||
340 | 3 | return null; |
|
341 | } |
||
342 | 20 | if ($fieldAst instanceof Query) { |
|
343 | 10 | $value[$alias] = $this->processQueryAST($fieldAst, $field, $resolvedValue); |
|
344 | } elseif ($fieldAst instanceof FieldAst) { |
||
345 | 19 | if (!TypeService::isLeafType($field->getType()->getNamedType()->getNullableType())) { |
|
346 | 1 | throw new ResolveException(sprintf('You have to specify fields for "%s"', $field->getName())); |
|
347 | } |
||
348 | 19 | $value[$alias] = $this->processFieldAST($fieldAst, $field, $resolvedValue); |
|
349 | } else { |
||
350 | 20 | return $value; |
|
351 | } |
||
352 | } |
||
353 | } |
||
354 | |||
355 | } |
||
356 | |||
357 | 20 | return $value; |
|
358 | } |
||
359 | |||
360 | protected function getFieldValidatedValue(FieldInterface $field, $value) |
||
361 | { |
||
362 | return ($this->resolveValidator->isValidValueForField($field, $value)) ? $this->getOutputValue($field->getType(), $value) : null; |
||
363 | } |
||
364 | |||
365 | 22 | protected function getOutputValue(AbstractType $type, $value) |
|
366 | { |
||
367 | 22 | return in_array($type->getKind(), [TypeMap::KIND_OBJECT, TypeMap::KIND_NON_NULL]) ? $value : $type->serialize($value); |
|
368 | } |
||
369 | |||
370 | 28 | public function getResponseData() |
|
371 | { |
||
372 | 28 | $result = []; |
|
373 | |||
374 | 28 | if (!empty($this->data)) { |
|
375 | 25 | $result['data'] = $this->data; |
|
376 | } |
||
377 | |||
378 | 28 | if ($this->executionContext->hasErrors()) { |
|
379 | 10 | $result['errors'] = $this->executionContext->getErrorsArray(); |
|
380 | } |
||
381 | |||
382 | 28 | return $result; |
|
383 | } |
||
384 | |||
385 | /** |
||
386 | * You can access ExecutionContext to check errors and inject dependencies |
||
387 | * |
||
388 | * @return ExecutionContext |
||
389 | */ |
||
390 | 9 | public function getExecutionContext() |
|
391 | { |
||
392 | 9 | return $this->executionContext; |
|
393 | } |
||
394 | |||
395 | /** |
||
396 | * Convenience function for attaching a MaxComplexityQueryVisitor($max) to the next processor run |
||
397 | * |
||
398 | * @param int $max |
||
399 | */ |
||
400 | 1 | public function setMaxComplexity($max) |
|
404 | |||
405 | /** |
||
406 | * Apply all of $reducers to this query. Example reducer operations: checking for maximum query complexity, |
||
407 | * performing look-ahead query planning, etc. |
||
408 | * |
||
409 | * @param AbstractType $queryType |
||
410 | * @param AbstractType $mutationType |
||
411 | * @param AbstractQueryVisitor[] $reducers |
||
412 | */ |
||
413 | 28 | protected function reduceQuery($queryType, $mutationType, array $reducers) |
|
421 | |||
422 | /** |
||
423 | * Entry point for the `walkQuery` routine. Execution bounces between here, where the reducer's ->visit() method |
||
424 | * is invoked, and `walkQuery` where we send in the scores from the `visit` call. |
||
425 | * |
||
426 | * @param Query $query |
||
427 | * @param AbstractType $currentLevelSchema |
||
428 | * @param AbstractQueryVisitor $reducer |
||
429 | */ |
||
430 | 2 | protected function doVisit(Query $query, $currentLevelSchema, $reducer) |
|
457 | |||
458 | /** |
||
459 | * Coroutine to walk the query and schema in DFS manner (see AbstractQueryVisitor docs for more info) and yield a |
||
460 | * tuple of (queryNode, schemaNode, childScore) |
||
461 | * |
||
462 | * childScore costs are accumulated via values sent into the coroutine. |
||
463 | * |
||
464 | * Most of the branching in this function is just to handle the different types in a query: Queries, Unions, |
||
465 | * Fragments (anonymous and named), and Fields. The core of the function is simple: recurse until we hit the base |
||
466 | * case of a Field and yield that back up to the visitor up in `doVisit`. |
||
467 | * |
||
468 | * @param Query|Field|FragmentInterface $queryNode |
||
469 | * @param FieldInterface $currentLevelAST |
||
470 | * |
||
471 | * @return \Generator |
||
472 | */ |
||
473 | 2 | protected function walkQuery($queryNode, FieldInterface $currentLevelAST) |
|
526 | } |
||
527 |
There are different options of fixing this problem.
If you want to be on the safe side, you can add an additional type-check:
If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:
Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.