Completed
Pull Request — 8.x-3.x (#653)
by Sebastian
02:46
created

SchemaPluginBase   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 484
Duplicated Lines 4.96 %

Coupling/Cohesion

Components 4
Dependencies 6

Importance

Changes 0
Metric Value
dl 24
loc 484
rs 8.72
c 0
b 0
f 0
wmc 46
lcom 4
cbo 6

27 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 14 1
A __construct() 0 21 1
A getSchema() 0 38 3
A getServer() 0 42 3
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 Symfony\Component\DependencyInjection\ContainerInterface;
26
27
abstract class SchemaPluginBase extends PluginBase implements SchemaPluginInterface, SchemaBuilderInterface, ContainerFactoryPluginInterface, CacheableDependencyInterface {
28
29
  /**
30
   * The field plugin manager.
31
   *
32
   * @var \Drupal\graphql\Plugin\FieldPluginManager
33
   */
34
  protected $fieldManager;
35
36
  /**
37
   * The mutation plugin manager.
38
   *
39
   * @var \Drupal\graphql\Plugin\MutationPluginManager
40
   */
41
  protected $mutationManager;
42
43
  /**
44
   * The subscription plugin manager.
45
   *
46
   * @var \Drupal\graphql\Plugin\SubscriptionPluginManager
47
   */
48
  protected $subscriptionManager;
49
50
  /**
51
   * The type manager aggregator service.
52
   *
53
   * @var \Drupal\graphql\Plugin\TypePluginManagerAggregator
54
   */
55
  protected $typeManagers;
56
57
  /**
58
   * Static cache of field definitions.
59
   *
60
   * @var array
61
   */
62
  protected $fields = [];
63
64
  /**
65
   * Static cache of mutation definitions.
66
   *
67
   * @var array
68
   */
69
  protected $mutations = [];
70
71
  /**
72
   * Static cache of subscription definitions.
73
   *
74
   * @var array
75
   */
76
  protected $subscriptions = [];
77
78
  /**
79
   * Static cache of type instances.
80
   *
81
   * @var array
82
   */
83
  protected $types = [];
84
85
  /**
86
   * The service parameters
87
   *
88
   * @var array
89
   */
90
  protected $parameters;
91
92
  /**
93
   * The query provider service.
94
   *
95
   * @var \Drupal\graphql\GraphQL\QueryProvider\QueryProviderInterface
96
   */
97
  protected $queryProvider;
98
99
  /**
100
   * The current user.
101
   *
102
   * @var \Drupal\Core\Session\AccountProxyInterface
103
   */
104
  protected $currentUser;
105
106
  /**
107
   * {@inheritdoc}
108
   */
109
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
110
    return new static(
111
      $configuration,
112
      $plugin_id,
113
      $plugin_definition,
114
      $container->get('plugin.manager.graphql.field'),
115
      $container->get('plugin.manager.graphql.mutation'),
116
      $container->get('plugin.manager.graphql.subscription'),
117
      $container->get('graphql.type_manager_aggregator'),
118
      $container->get('graphql.query_provider'),
119
      $container->get('current_user'),
120
      $container->getParameter('graphql.config')
121
    );
122
  }
123
124
  /**
125
   * SchemaPluginBase constructor.
126
   *
127
   * @param array $configuration
128
   *   The plugin configuration array.
129
   * @param string $pluginId
130
   *   The plugin id.
131
   * @param array $pluginDefinition
132
   *   The plugin definition array.
133
   * @param \Drupal\graphql\Plugin\FieldPluginManager $fieldManager
134
   *   The field plugin manager.
135
   * @param \Drupal\graphql\Plugin\MutationPluginManager $mutationManager
136
   *   The mutation plugin manager.
137
   * @param \Drupal\graphql\Plugin\SubscriptionPluginManager $subscriptionManager
138
   *   The subscription plugin manager.
139
   * @param \Drupal\graphql\Plugin\TypePluginManagerAggregator $typeManagers
140
   *   The type manager aggregator service.
141
   * @param \Drupal\graphql\GraphQL\QueryProvider\QueryProviderInterface $queryProvider
142
   *   The query provider service.
143
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
144
   *   The current user.
145
   * @param array $parameters
146
   */
147
  public function __construct(
148
    $configuration,
149
    $pluginId,
150
    $pluginDefinition,
151
    FieldPluginManager $fieldManager,
152
    MutationPluginManager $mutationManager,
153
    SubscriptionPluginManager $subscriptionManager,
154
    TypePluginManagerAggregator $typeManagers,
155
    QueryProviderInterface $queryProvider,
156
    AccountProxyInterface $currentUser,
157
    array $parameters
158
  ) {
159
    parent::__construct($configuration, $pluginId, $pluginDefinition);
160
    $this->fieldManager = $fieldManager;
161
    $this->mutationManager = $mutationManager;
162
    $this->subscriptionManager = $subscriptionManager;
163
    $this->typeManagers = $typeManagers;
164
    $this->queryProvider = $queryProvider;
165
    $this->currentUser = $currentUser;
166
    $this->parameters = $parameters;
167
  }
168
169
  /**
170
   * {@inheritdoc}
171
   */
172
  public function getSchema() {
173
    $config = new SchemaConfig();
174
175
    if ($this->hasMutations()) {
176
      $config->setMutation(new ObjectType([
177
        'name' => 'MutationRoot',
178
        'fields' => function () {
179
          return $this->getMutations();
180
        },
181
      ]));
182
    }
183
184
    if ($this->hasSubscriptions()) {
185
      $config->setSubscription(new ObjectType([
186
        'name' => 'SubscriptionRoot',
187
        'fields' => function () {
188
          return $this->getSubscriptions();
189
        },
190
      ]));
191
    }
192
193
    $config->setQuery(new ObjectType([
194
      'name' => 'QueryRoot',
195
      'fields' => function () {
196
        return $this->getFields('Root');
197
      },
198
    ]));
199
200
    $config->setTypes(function () {
201
      return $this->getTypes();
202
    });
203
204
    $config->setTypeLoader(function ($name) {
205
      return $this->getType($name);
206
    });
207
208
    return new Schema($config);
209
  }
210
211
  /**
212
   * {@inheritdoc}
213
   */
214
  public function getServer() {
215
    // If the current user has appropriate permissions, allow to bypass
216
    // the secure fields restriction.
217
    $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...
218
219
    // Create the server config.
220
    $config = ServerConfig::create();
221
222
    // Each document (e.g. in a batch query) gets its own resolve context. This
223
    // allows us to collect the cache metadata and contextual values (e.g.
224
    // inheritance for language) for each query separately.
225
    $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...
226
      // Each document (e.g. in a batch query) gets its own resolve context. This
227
      // allows us to collect the cache metadata and contextual values (e.g.
228
      // inheritance for language) for each query separately.
229
      $context = new ResolveContext($globals);
230
      $context->addCacheTags(['graphql_response']);
231
      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...
232
        $context->addCacheableDependency($this);
233
      }
234
235
      return $context;
236
    });
237
238
    $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...
239
      if (isset($params->queryId)) {
240
        // Assume that pre-parsed documents are already validated. This allows
241
        // us to store pre-validated query documents e.g. for persisted queries
242
        // effectively improving performance by skipping run-time validation.
243
        return [];
244
      }
245
246
      return array_values(DocumentValidator::defaultRules());
247
    });
248
249
    $config->setPersistentQueryLoader([$this->queryProvider, 'getQuery']);
250
    $config->setQueryBatching(TRUE);
251
    $config->setDebug(!!$this->parameters['development']);
252
    $config->setSchema($this->getSchema());
253
254
    return $config;
255
  }
256
257
  /**
258
  /**
259
   * {@inheritdoc}
260
   */
261
  public function hasFields($type) {
262
    return isset($this->pluginDefinition['field_association_map'][$type]);
263
  }
264
265
  /**
266
   * {@inheritdoc}
267
   */
268
  public function hasMutations() {
269
    return !empty($this->pluginDefinition['mutation_map']);
270
  }
271
272
  /**
273
   * {@inheritdoc}
274
   */
275
  public function hasSubscriptions() {
276
    return !empty($this->pluginDefinition['subscription_map']);
277
  }
278
279
  /**
280
   * {@inheritdoc}
281
   */
282
  public function hasType($name) {
283
    return isset($this->pluginDefinition['type_map'][$name]);
284
  }
285
286
  /**
287
   * {@inheritdoc}
288
   */
289
  public function getFields($type) {
290
    $association = $this->pluginDefinition['field_association_map'];
291
    $fields = $this->pluginDefinition['field_map'];
292
293
    if (isset($association[$type])) {
294
      return $this->processFields(array_map(function ($id) use ($fields) {
295
        return $fields[$id];
296
      }, $association[$type]));
297
    }
298
299
    return [];
300
  }
301
302
  /**
303
   * {@inheritdoc}
304
   */
305
  public function getMutations() {
306
    return $this->processMutations($this->pluginDefinition['mutation_map']);
307
  }
308
309
  /**
310
   * {@inheritdoc}
311
   */
312
  public function getSubscriptions() {
313
    return $this->processSubscriptions($this->pluginDefinition['subscription_map']);
314
  }
315
316
  /**
317
   * {@inheritdoc}
318
   */
319
  public function getTypes() {
320
    return array_map(function ($name) {
321
      return $this->getType($name);
322
    }, array_keys($this->pluginDefinition['type_map']));
323
  }
324
325
  /**
326
   * {@inheritdoc}
327
   */
328
  public function getSubTypes($name) {
329
    $association = $this->pluginDefinition['type_association_map'];
330
    return isset($association[$name]) ? $association[$name] : [];
331
  }
332
333
  /**
334
   * {@inheritdoc}
335
   */
336
  public function resolveType($name, $value, ResolveContext $context, ResolveInfo $info) {
337
    $association = $this->pluginDefinition['type_association_map'];
338
    $types = $this->pluginDefinition['type_map'];
339
    if (!isset($association[$name])) {
340
      return NULL;
341
    }
342
343
    foreach ($association[$name] as $type) {
344
      // TODO: Try to avoid loading the type for the check. Consider to make it static!
345
      if (isset($types[$type]) && $instance = $this->buildType($types[$type])) {
346
        if ($instance->isTypeOf($value, $context, $info)) {
347
          return $instance;
348
        }
349
      }
350
    }
351
352
    return NULL;
353
  }
354
355
  /**
356
   * {@inheritdoc}
357
   */
358
  public function getType($name) {
359
    $types = $this->pluginDefinition['type_map'];
360
    $references = $this->pluginDefinition['type_reference_map'];
361
    if (isset($types[$name])) {
362
      return $this->buildType($this->pluginDefinition['type_map'][$name]);
363
    }
364
365
    do {
366
      if (isset($references[$name])) {
367
        return $this->buildType($types[$references[$name]]);
368
      }
369
    } while (($pos = strpos($name, ':')) !== FALSE && $name = substr($name, 0, $pos));
370
371
    throw new \LogicException(sprintf('Missing type %s.', $name));
372
  }
373
374
  /**
375
   * {@inheritdoc}
376
   */
377
  public function processMutations($mutations) {
378
    return array_map([$this, 'buildMutation'], $mutations);
379
  }
380
381
  /**
382
   * {@inheritdoc}
383
   */
384
  public function processSubscriptions($subscriptions) {
385
    return array_map([$this, 'buildSubscription'], $subscriptions);
386
  }
387
388
  /**
389
   * {@inheritdoc}
390
   */
391
  public function processFields($fields) {
392
    return array_map([$this, 'buildField'], $fields);
393
  }
394
395
  /**
396
   * {@inheritdoc}
397
   */
398
  public function processArguments($args) {
399
    return array_map(function ($arg) {
400
      return [
401
        'type' => $this->processType($arg['type']),
402
      ] + $arg;
403
    }, $args);
404
  }
405
406
  /**
407
   * {@inheritdoc}
408
   */
409
  public function processType($type) {
410
    list($type, $decorators) = $type;
411
412
    return array_reduce($decorators, function ($type, $decorator) {
413
      return $decorator($type);
414
    }, $this->getType($type));
415
  }
416
417
  /**
418
   * Retrieves the type instance for the given reference.
419
   *
420
   * @param array $type
421
   *   The type reference.
422
   *
423
   * @return \GraphQL\Type\Definition\Type
424
   *   The type instance.
425
   */
426
  protected function buildType($type) {
427
    if (!isset($this->types[$type['id']])) {
428
      $creator = [$type['class'], 'createInstance'];
429
      $manager = $this->typeManagers->getTypeManager($type['type']);
430
      $this->types[$type['id']] = $creator($this, $manager, $type['definition'], $type['id']);
431
    }
432
433
    return $this->types[$type['id']];
434
  }
435
436
  /**
437
   * Retrieves the field definition for a given field reference.
438
   *
439
   * @param array $field
440
   *   The type reference.
441
   *
442
   * @return array
443
   *   The field definition.
444
   */
445 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...
446
    if (!isset($this->fields[$field['id']])) {
447
      $creator = [$field['class'], 'createInstance'];
448
      $this->fields[$field['id']] = $creator($this, $this->fieldManager, $field['definition'], $field['id']);
449
    }
450
451
    return $this->fields[$field['id']];
452
  }
453
454
  /**
455
   * Retrieves the mutation definition for a given field reference.
456
   *
457
   * @param array $mutation
458
   *   The mutation reference.
459
   *
460
   * @return array
461
   *   The mutation definition.
462
   */
463 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...
464
    if (!isset($this->mutations[$mutation['id']])) {
465
      $creator = [$mutation['class'], 'createInstance'];
466
      $this->mutations[$mutation['id']] = $creator($this, $this->mutationManager, $mutation['definition'], $mutation['id']);
467
    }
468
469
    return $this->mutations[$mutation['id']];
470
  }
471
472
  /**
473
   * Retrieves the subscription definition for a given field reference.
474
   *
475
   * @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...
476
   *   The subscription reference.
477
   *
478
   * @return array
479
   *   The subscription definition.
480
   */
481 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...
482
    if (!isset($this->subscriptions[$subscription['id']])) {
483
      $creator = [$subscription['class'], 'createInstance'];
484
      $this->subscriptions[$subscription['id']] = $creator($this, $this->subscriptionManager, $subscription['definition'], $subscription['id']);
485
    }
486
487
    return $this->subscriptions[$subscription['id']];
488
  }
489
490
  /**
491
   * {@inheritdoc}
492
   */
493
  public function getCacheContexts() {
494
    return [];
495
  }
496
497
  /**
498
   * {@inheritdoc}
499
   */
500
  public function getCacheTags() {
501
    return $this->pluginDefinition['schema_cache_tags'];
502
  }
503
504
  /**
505
   * {@inheritdoc}
506
   */
507
  public function getCacheMaxAge() {
508
    return $this->pluginDefinition['schema_cache_max_age'];
509
  }
510
}
511