Completed
Push — 8.x-3.x ( 586f2a...496612 )
by Sebastian
20:25 queued 17:50
created

SchemaPluginBase   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 515
Duplicated Lines 4.66 %

Coupling/Cohesion

Components 4
Dependencies 6

Importance

Changes 0
Metric Value
dl 24
loc 515
rs 8.48
c 0
b 0
f 0
wmc 49
lcom 4
cbo 6

28 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 15 1
A __construct() 0 23 1
A getSchema() 0 38 3
A validateSchema() 0 3 1
B getServer() 0 53 5
A hasFields() 0 3 1
A hasMutations() 0 3 1
A hasSubscriptions() 0 3 1
A hasType() 0 3 1
A getFields() 0 12 2
A getMutations() 0 3 1
A getSubscriptions() 0 3 1
A getTypes() 0 5 1
A getSubTypes() 0 4 2
A resolveType() 0 18 6
A getType() 0 15 5
A processMutations() 0 3 1
A processSubscriptions() 0 3 1
A processFields() 0 3 1
A processArguments() 0 7 1
A processType() 0 7 1
A buildType() 0 9 2
A buildField() 8 8 2
A buildMutation() 8 8 2
A buildSubscription() 8 8 2
A getCacheContexts() 0 3 1
A getCacheTags() 0 3 1
A getCacheMaxAge() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

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 Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SchemaPluginBase 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 SchemaPluginBase, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Drupal\graphql\Plugin\GraphQL\Schemas;
4
5
use Drupal\Component\Plugin\PluginBase;
6
use Drupal\Core\Cache\CacheableDependencyInterface;
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\Core\Session\AccountProxyInterface;
9
use Drupal\graphql\GraphQL\Execution\ResolveContext;
10
use Drupal\graphql\GraphQL\QueryProvider\QueryProviderInterface;
11
use Drupal\graphql\Plugin\FieldPluginManager;
12
use Drupal\graphql\Plugin\MutationPluginManager;
13
use Drupal\graphql\Plugin\SubscriptionPluginManager;
14
use Drupal\graphql\Plugin\SchemaBuilderInterface;
15
use Drupal\graphql\Plugin\SchemaPluginInterface;
16
use Drupal\graphql\Plugin\TypePluginManagerAggregator;
17
use GraphQL\Language\AST\DocumentNode;
18
use GraphQL\Server\OperationParams;
19
use GraphQL\Server\ServerConfig;
20
use GraphQL\Type\Definition\ObjectType;
21
use GraphQL\Type\Definition\ResolveInfo;
22
use GraphQL\Type\Schema;
23
use GraphQL\Type\SchemaConfig;
24
use GraphQL\Validator\DocumentValidator;
25
use Psr\Log\LoggerInterface;
26
use Symfony\Component\DependencyInjection\ContainerInterface;
27
28
abstract class SchemaPluginBase extends PluginBase implements SchemaPluginInterface, SchemaBuilderInterface, ContainerFactoryPluginInterface, CacheableDependencyInterface {
29
30
  /**
31
   * The field plugin manager.
32
   *
33
   * @var \Drupal\graphql\Plugin\FieldPluginManager
34
   */
35
  protected $fieldManager;
36
37
  /**
38
   * The mutation plugin manager.
39
   *
40
   * @var \Drupal\graphql\Plugin\MutationPluginManager
41
   */
42
  protected $mutationManager;
43
44
  /**
45
   * The subscription plugin manager.
46
   *
47
   * @var \Drupal\graphql\Plugin\SubscriptionPluginManager
48
   */
49
  protected $subscriptionManager;
50
51
  /**
52
   * The type manager aggregator service.
53
   *
54
   * @var \Drupal\graphql\Plugin\TypePluginManagerAggregator
55
   */
56
  protected $typeManagers;
57
58
  /**
59
   * Static cache of field definitions.
60
   *
61
   * @var array
62
   */
63
  protected $fields = [];
64
65
  /**
66
   * Static cache of mutation definitions.
67
   *
68
   * @var array
69
   */
70
  protected $mutations = [];
71
72
  /**
73
   * Static cache of subscription definitions.
74
   *
75
   * @var array
76
   */
77
  protected $subscriptions = [];
78
79
  /**
80
   * Static cache of type instances.
81
   *
82
   * @var array
83
   */
84
  protected $types = [];
85
86
  /**
87
   * The service parameters
88
   *
89
   * @var array
90
   */
91
  protected $parameters;
92
93
  /**
94
   * The query provider service.
95
   *
96
   * @var \Drupal\graphql\GraphQL\QueryProvider\QueryProviderInterface
97
   */
98
  protected $queryProvider;
99
100
  /**
101
   * The current user.
102
   *
103
   * @var \Drupal\Core\Session\AccountProxyInterface
104
   */
105
  protected $currentUser;
106
107
  /**
108
   * The logger service.
109
   *
110
   * @var \Psr\Log\LoggerInterface
111
   */
112
  protected $logger;
113
114
  /**
115
   * {@inheritdoc}
116
   */
117
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
118
    return new static(
119
      $configuration,
120
      $plugin_id,
121
      $plugin_definition,
122
      $container->get('plugin.manager.graphql.field'),
123
      $container->get('plugin.manager.graphql.mutation'),
124
      $container->get('plugin.manager.graphql.subscription'),
125
      $container->get('graphql.type_manager_aggregator'),
126
      $container->get('graphql.query_provider'),
127
      $container->get('current_user'),
128
      $container->get('logger.channel.graphql'),
129
      $container->getParameter('graphql.config')
130
    );
131
  }
132
133
  /**
134
   * SchemaPluginBase constructor.
135
   *
136
   * @param array $configuration
137
   *   The plugin configuration array.
138
   * @param string $pluginId
139
   *   The plugin id.
140
   * @param array $pluginDefinition
141
   *   The plugin definition array.
142
   * @param \Drupal\graphql\Plugin\FieldPluginManager $fieldManager
143
   *   The field plugin manager.
144
   * @param \Drupal\graphql\Plugin\MutationPluginManager $mutationManager
145
   *   The mutation plugin manager.
146
   * @param \Drupal\graphql\Plugin\SubscriptionPluginManager $subscriptionManager
147
   *   The subscription plugin manager.
148
   * @param \Drupal\graphql\Plugin\TypePluginManagerAggregator $typeManagers
149
   *   The type manager aggregator service.
150
   * @param \Drupal\graphql\GraphQL\QueryProvider\QueryProviderInterface $queryProvider
151
   *   The query provider service.
152
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
153
   *   The current user.
154
   * @param \Psr\Log\LoggerInterface $logger
155
   *   The logger service.
156
   * @param array $parameters
157
   *   The service parameters.
158
   */
159
  public function __construct(
160
    $configuration,
161
    $pluginId,
162
    $pluginDefinition,
163
    FieldPluginManager $fieldManager,
164
    MutationPluginManager $mutationManager,
165
    SubscriptionPluginManager $subscriptionManager,
166
    TypePluginManagerAggregator $typeManagers,
167
    QueryProviderInterface $queryProvider,
168
    AccountProxyInterface $currentUser,
169
    LoggerInterface $logger,
170
    array $parameters
171
  ) {
172
    parent::__construct($configuration, $pluginId, $pluginDefinition);
173
    $this->fieldManager = $fieldManager;
174
    $this->mutationManager = $mutationManager;
175
    $this->subscriptionManager = $subscriptionManager;
176
    $this->typeManagers = $typeManagers;
177
    $this->queryProvider = $queryProvider;
178
    $this->currentUser = $currentUser;
179
    $this->parameters = $parameters;
180
    $this->logger = $logger;
181
  }
182
183
  /**
184
   * {@inheritdoc}
185
   */
186
  public function getSchema() {
187
    $config = new SchemaConfig();
188
189
    if ($this->hasMutations()) {
190
      $config->setMutation(new ObjectType([
191
        'name' => 'Mutation',
192
        'fields' => function () {
193
          return $this->getMutations();
194
        },
195
      ]));
196
    }
197
198
    if ($this->hasSubscriptions()) {
199
      $config->setSubscription(new ObjectType([
200
        'name' => 'Subscription',
201
        'fields' => function () {
202
          return $this->getSubscriptions();
203
        },
204
      ]));
205
    }
206
207
    $config->setQuery(new ObjectType([
208
      'name' => 'Query',
209
      'fields' => function () {
210
        return $this->getFields('Root');
211
      },
212
    ]));
213
214
    $config->setTypes(function () {
215
      return $this->getTypes();
216
    });
217
218
    $config->setTypeLoader(function ($name) {
219
      return $this->getType($name);
220
    });
221
222
    return new Schema($config);
223
  }
224
225
  /**
226
   * {@inheritdoc}
227
   */
228
  public function validateSchema() {
229
    return NULL;
230
  }
231
232
  /**
233
   * {@inheritdoc}
234
   */
235
  public function getServer() {
236
    // If the current user has appropriate permissions, allow to bypass
237
    // the secure fields restriction.
238
    $globals['bypass field security'] = $this->currentUser->hasPermission('bypass graphql field security');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$globals was never initialized. Although not strictly required by PHP, it is generally a good practice to add $globals = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
239
240
    // Create the server config.
241
    $config = ServerConfig::create();
242
243
    // Each document (e.g. in a batch query) gets its own resolve context. This
244
    // allows us to collect the cache metadata and contextual values (e.g.
245
    // inheritance for language) for each query separately.
246
    $config->setContext(function ($params, $document, $operation) use ($globals) {
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $document is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $operation is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
247
      // Each document (e.g. in a batch query) gets its own resolve context. This
248
      // allows us to collect the cache metadata and contextual values (e.g.
249
      // inheritance for language) for each query separately.
250
      $context = new ResolveContext($globals);
251
      $context->addCacheTags(['graphql_response']);
252
      if ($this instanceof CacheableDependencyInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Cache\CacheableDependencyInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
253
        $context->addCacheableDependency($this);
254
      }
255
256
      return $context;
257
    });
258
259
    $config->setValidationRules(function (OperationParams $params, DocumentNode $document, $operation) {
0 ignored issues
show
Unused Code introduced by
The parameter $document is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $operation is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
260
      if (isset($params->queryId)) {
261
        // Assume that pre-parsed documents are already validated. This allows
262
        // us to store pre-validated query documents e.g. for persisted queries
263
        // effectively improving performance by skipping run-time validation.
264
        return [];
265
      }
266
267
      return array_values(DocumentValidator::defaultRules());
268
    });
269
270
    $config->setPersistentQueryLoader([$this->queryProvider, 'getQuery']);
271
    $config->setQueryBatching(TRUE);
272
    $config->setDebug(!!$this->parameters['development']);
273
    $config->setSchema($this->getSchema());
274
275
    // Log errors in development mode.
276
    if (!!$this->parameters['development']) {
277
      $config->setErrorsHandler(function (array $errors, callable $formatter) {
278
        foreach ($errors as $error) {
279
          $this->logger->error($error->getMessage());
280
        }
281
282
        return array_map($formatter, $errors);
283
      });
284
    }
285
286
    return $config;
287
  }
288
289
  /**
290
  /**
291
   * {@inheritdoc}
292
   */
293
  public function hasFields($type) {
294
    return isset($this->pluginDefinition['field_association_map'][$type]);
295
  }
296
297
  /**
298
   * {@inheritdoc}
299
   */
300
  public function hasMutations() {
301
    return !empty($this->pluginDefinition['mutation_map']);
302
  }
303
304
  /**
305
   * {@inheritdoc}
306
   */
307
  public function hasSubscriptions() {
308
    return !empty($this->pluginDefinition['subscription_map']);
309
  }
310
311
  /**
312
   * {@inheritdoc}
313
   */
314
  public function hasType($name) {
315
    return isset($this->pluginDefinition['type_map'][$name]);
316
  }
317
318
  /**
319
   * {@inheritdoc}
320
   */
321
  public function getFields($type) {
322
    $association = $this->pluginDefinition['field_association_map'];
323
    $fields = $this->pluginDefinition['field_map'];
324
325
    if (isset($association[$type])) {
326
      return $this->processFields(array_map(function ($id) use ($fields) {
327
        return $fields[$id];
328
      }, $association[$type]));
329
    }
330
331
    return [];
332
  }
333
334
  /**
335
   * {@inheritdoc}
336
   */
337
  public function getMutations() {
338
    return $this->processMutations($this->pluginDefinition['mutation_map']);
339
  }
340
341
  /**
342
   * {@inheritdoc}
343
   */
344
  public function getSubscriptions() {
345
    return $this->processSubscriptions($this->pluginDefinition['subscription_map']);
346
  }
347
348
  /**
349
   * {@inheritdoc}
350
   */
351
  public function getTypes() {
352
    return array_map(function ($name) {
353
      return $this->getType($name);
354
    }, array_keys($this->pluginDefinition['type_map']));
355
  }
356
357
  /**
358
   * {@inheritdoc}
359
   */
360
  public function getSubTypes($name) {
361
    $association = $this->pluginDefinition['type_association_map'];
362
    return isset($association[$name]) ? $association[$name] : [];
363
  }
364
365
  /**
366
   * {@inheritdoc}
367
   */
368
  public function resolveType($name, $value, ResolveContext $context, ResolveInfo $info) {
369
    $association = $this->pluginDefinition['type_association_map'];
370
    $types = $this->pluginDefinition['type_map'];
371
    if (!isset($association[$name])) {
372
      return NULL;
373
    }
374
375
    foreach ($association[$name] as $type) {
376
      // TODO: Try to avoid loading the type for the check. Consider to make it static!
377
      if (isset($types[$type]) && $instance = $this->buildType($types[$type])) {
378
        if ($instance->isTypeOf($value, $context, $info)) {
0 ignored issues
show
Bug introduced by
The method isTypeOf() does not exist on GraphQL\Type\Definition\Type. Did you maybe mean isType()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
379
          return $instance;
380
        }
381
      }
382
    }
383
384
    return NULL;
385
  }
386
387
  /**
388
   * {@inheritdoc}
389
   */
390
  public function getType($name) {
391
    $types = $this->pluginDefinition['type_map'];
392
    $references = $this->pluginDefinition['type_reference_map'];
393
    if (isset($types[$name])) {
394
      return $this->buildType($this->pluginDefinition['type_map'][$name]);
395
    }
396
397
    do {
398
      if (isset($references[$name])) {
399
        return $this->buildType($types[$references[$name]]);
400
      }
401
    } while (($pos = strpos($name, ':')) !== FALSE && $name = substr($name, 0, $pos));
402
403
    throw new \LogicException(sprintf('Missing type %s.', $name));
404
  }
405
406
  /**
407
   * {@inheritdoc}
408
   */
409
  public function processMutations(array $mutations) {
410
    return array_map([$this, 'buildMutation'], $mutations);
411
  }
412
413
  /**
414
   * {@inheritdoc}
415
   */
416
  public function processSubscriptions(array $subscriptions) {
417
    return array_map([$this, 'buildSubscription'], $subscriptions);
418
  }
419
420
  /**
421
   * {@inheritdoc}
422
   */
423
  public function processFields(array $fields) {
424
    return array_map([$this, 'buildField'], $fields);
425
  }
426
427
  /**
428
   * {@inheritdoc}
429
   */
430
  public function processArguments(array $args) {
431
    return array_map(function ($arg) {
432
      return [
433
        'type' => $this->processType($arg['type']),
434
      ] + $arg;
435
    }, $args);
436
  }
437
438
  /**
439
   * {@inheritdoc}
440
   */
441
  public function processType(array $type) {
442
    list($type, $decorators) = $type;
443
444
    return array_reduce($decorators, function ($type, $decorator) {
445
      return $decorator($type);
446
    }, $this->getType($type));
447
  }
448
449
  /**
450
   * Retrieves the type instance for the given reference.
451
   *
452
   * @param array $type
453
   *   The type reference.
454
   *
455
   * @return \GraphQL\Type\Definition\Type
456
   *   The type instance.
457
   */
458
  protected function buildType($type) {
459
    if (!isset($this->types[$type['id']])) {
460
      $creator = [$type['class'], 'createInstance'];
461
      $manager = $this->typeManagers->getTypeManager($type['type']);
462
      $this->types[$type['id']] = $creator($this, $manager, $type['definition'], $type['id']);
463
    }
464
465
    return $this->types[$type['id']];
466
  }
467
468
  /**
469
   * Retrieves the field definition for a given field reference.
470
   *
471
   * @param array $field
472
   *   The type reference.
473
   *
474
   * @return array
475
   *   The field definition.
476
   */
477 View Code Duplication
  protected function buildField($field) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
478
    if (!isset($this->fields[$field['id']])) {
479
      $creator = [$field['class'], 'createInstance'];
480
      $this->fields[$field['id']] = $creator($this, $this->fieldManager, $field['definition'], $field['id']);
481
    }
482
483
    return $this->fields[$field['id']];
484
  }
485
486
  /**
487
   * Retrieves the mutation definition for a given field reference.
488
   *
489
   * @param array $mutation
490
   *   The mutation reference.
491
   *
492
   * @return array
493
   *   The mutation definition.
494
   */
495 View Code Duplication
  protected function buildMutation($mutation) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
496
    if (!isset($this->mutations[$mutation['id']])) {
497
      $creator = [$mutation['class'], 'createInstance'];
498
      $this->mutations[$mutation['id']] = $creator($this, $this->mutationManager, $mutation['definition'], $mutation['id']);
499
    }
500
501
    return $this->mutations[$mutation['id']];
502
  }
503
504
  /**
505
   * Retrieves the subscription definition for a given field reference.
506
   *
507
   * @param array $mutation
0 ignored issues
show
Bug introduced by
There is no parameter named $mutation. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
508
   *   The subscription reference.
509
   *
510
   * @return array
511
   *   The subscription definition.
512
   */
513 View Code Duplication
  protected function buildSubscription($subscription) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
514
    if (!isset($this->subscriptions[$subscription['id']])) {
515
      $creator = [$subscription['class'], 'createInstance'];
516
      $this->subscriptions[$subscription['id']] = $creator($this, $this->subscriptionManager, $subscription['definition'], $subscription['id']);
517
    }
518
519
    return $this->subscriptions[$subscription['id']];
520
  }
521
522
  /**
523
   * {@inheritdoc}
524
   */
525
  public function getCacheContexts() {
526
    return [];
527
  }
528
529
  /**
530
   * {@inheritdoc}
531
   */
532
  public function getCacheTags() {
533
    return $this->pluginDefinition['schema_cache_tags'];
534
  }
535
536
  /**
537
   * {@inheritdoc}
538
   */
539
  public function getCacheMaxAge() {
540
    return $this->pluginDefinition['schema_cache_max_age'];
541
  }
542
}
543