Completed
Push — 8.x-3.x ( b9394b...35ad71 )
by Sebastian
07:07
created

SchemaPluginBase::getServer()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 1
nop 0
dl 0
loc 52
rs 9.0472
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    // Always log the errors.
276
    $config->setErrorsHandler(function (array $errors, callable $formatter) {
277
      /** @var \GraphQL\Error\Error $error */
278
      foreach ($errors as $error) {
279
        $this->logger->error($error->getMessage());
280
      }
281
282
      return array_map($formatter, $errors);
283
    });
284
285
    return $config;
286
  }
287
288
  /**
289
  /**
290
   * {@inheritdoc}
291
   */
292
  public function hasFields($type) {
293
    return isset($this->pluginDefinition['field_association_map'][$type]);
294
  }
295
296
  /**
297
   * {@inheritdoc}
298
   */
299
  public function hasMutations() {
300
    return !empty($this->pluginDefinition['mutation_map']);
301
  }
302
303
  /**
304
   * {@inheritdoc}
305
   */
306
  public function hasSubscriptions() {
307
    return !empty($this->pluginDefinition['subscription_map']);
308
  }
309
310
  /**
311
   * {@inheritdoc}
312
   */
313
  public function hasType($name) {
314
    return isset($this->pluginDefinition['type_map'][$name]);
315
  }
316
317
  /**
318
   * {@inheritdoc}
319
   */
320
  public function getFields($type) {
321
    $association = $this->pluginDefinition['field_association_map'];
322
    $fields = $this->pluginDefinition['field_map'];
323
324
    if (isset($association[$type])) {
325
      return $this->processFields(array_map(function ($id) use ($fields) {
326
        return $fields[$id];
327
      }, $association[$type]));
328
    }
329
330
    return [];
331
  }
332
333
  /**
334
   * {@inheritdoc}
335
   */
336
  public function getMutations() {
337
    return $this->processMutations($this->pluginDefinition['mutation_map']);
338
  }
339
340
  /**
341
   * {@inheritdoc}
342
   */
343
  public function getSubscriptions() {
344
    return $this->processSubscriptions($this->pluginDefinition['subscription_map']);
345
  }
346
347
  /**
348
   * {@inheritdoc}
349
   */
350
  public function getTypes() {
351
    return array_map(function ($name) {
352
      return $this->getType($name);
353
    }, array_keys($this->pluginDefinition['type_map']));
354
  }
355
356
  /**
357
   * {@inheritdoc}
358
   */
359
  public function getSubTypes($name) {
360
    $association = $this->pluginDefinition['type_association_map'];
361
    return isset($association[$name]) ? $association[$name] : [];
362
  }
363
364
  /**
365
   * {@inheritdoc}
366
   */
367
  public function resolveType($name, $value, ResolveContext $context, ResolveInfo $info) {
368
    $association = $this->pluginDefinition['type_association_map'];
369
    $types = $this->pluginDefinition['type_map'];
370
    if (!isset($association[$name])) {
371
      return NULL;
372
    }
373
374
    foreach ($association[$name] as $type) {
375
      // TODO: Try to avoid loading the type for the check. Consider to make it static!
376
      if (isset($types[$type]) && $instance = $this->buildType($types[$type])) {
377
        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...
378
          return $instance;
379
        }
380
      }
381
    }
382
383
    return NULL;
384
  }
385
386
  /**
387
   * {@inheritdoc}
388
   */
389
  public function getType($name) {
390
    $types = $this->pluginDefinition['type_map'];
391
    $references = $this->pluginDefinition['type_reference_map'];
392
    if (isset($types[$name])) {
393
      return $this->buildType($this->pluginDefinition['type_map'][$name]);
394
    }
395
396
    do {
397
      if (isset($references[$name])) {
398
        return $this->buildType($types[$references[$name]]);
399
      }
400
    } while (($pos = strpos($name, ':')) !== FALSE && $name = substr($name, 0, $pos));
401
402
    throw new \LogicException(sprintf('Missing type %s.', $name));
403
  }
404
405
  /**
406
   * {@inheritdoc}
407
   */
408
  public function processMutations(array $mutations) {
409
    return array_map([$this, 'buildMutation'], $mutations);
410
  }
411
412
  /**
413
   * {@inheritdoc}
414
   */
415
  public function processSubscriptions(array $subscriptions) {
416
    return array_map([$this, 'buildSubscription'], $subscriptions);
417
  }
418
419
  /**
420
   * {@inheritdoc}
421
   */
422
  public function processFields(array $fields) {
423
    return array_map([$this, 'buildField'], $fields);
424
  }
425
426
  /**
427
   * {@inheritdoc}
428
   */
429
  public function processArguments(array $args) {
430
    return array_map(function ($arg) {
431
      return [
432
        'type' => $this->processType($arg['type']),
433
      ] + $arg;
434
    }, $args);
435
  }
436
437
  /**
438
   * {@inheritdoc}
439
   */
440
  public function processType(array $type) {
441
    list($type, $decorators) = $type;
442
443
    return array_reduce($decorators, function ($type, $decorator) {
444
      return $decorator($type);
445
    }, $this->getType($type));
446
  }
447
448
  /**
449
   * Retrieves the type instance for the given reference.
450
   *
451
   * @param array $type
452
   *   The type reference.
453
   *
454
   * @return \GraphQL\Type\Definition\Type
455
   *   The type instance.
456
   */
457
  protected function buildType($type) {
458
    if (!isset($this->types[$type['id']])) {
459
      $creator = [$type['class'], 'createInstance'];
460
      $manager = $this->typeManagers->getTypeManager($type['type']);
461
      $this->types[$type['id']] = $creator($this, $manager, $type['definition'], $type['id']);
462
    }
463
464
    return $this->types[$type['id']];
465
  }
466
467
  /**
468
   * Retrieves the field definition for a given field reference.
469
   *
470
   * @param array $field
471
   *   The type reference.
472
   *
473
   * @return array
474
   *   The field definition.
475
   */
476 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...
477
    if (!isset($this->fields[$field['id']])) {
478
      $creator = [$field['class'], 'createInstance'];
479
      $this->fields[$field['id']] = $creator($this, $this->fieldManager, $field['definition'], $field['id']);
480
    }
481
482
    return $this->fields[$field['id']];
483
  }
484
485
  /**
486
   * Retrieves the mutation definition for a given field reference.
487
   *
488
   * @param array $mutation
489
   *   The mutation reference.
490
   *
491
   * @return array
492
   *   The mutation definition.
493
   */
494 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...
495
    if (!isset($this->mutations[$mutation['id']])) {
496
      $creator = [$mutation['class'], 'createInstance'];
497
      $this->mutations[$mutation['id']] = $creator($this, $this->mutationManager, $mutation['definition'], $mutation['id']);
498
    }
499
500
    return $this->mutations[$mutation['id']];
501
  }
502
503
  /**
504
   * Retrieves the subscription definition for a given field reference.
505
   *
506
   * @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...
507
   *   The subscription reference.
508
   *
509
   * @return array
510
   *   The subscription definition.
511
   */
512 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...
513
    if (!isset($this->subscriptions[$subscription['id']])) {
514
      $creator = [$subscription['class'], 'createInstance'];
515
      $this->subscriptions[$subscription['id']] = $creator($this, $this->subscriptionManager, $subscription['definition'], $subscription['id']);
516
    }
517
518
    return $this->subscriptions[$subscription['id']];
519
  }
520
521
  /**
522
   * {@inheritdoc}
523
   */
524
  public function getCacheContexts() {
525
    return [];
526
  }
527
528
  /**
529
   * {@inheritdoc}
530
   */
531
  public function getCacheTags() {
532
    return $this->pluginDefinition['schema_cache_tags'];
533
  }
534
535
  /**
536
   * {@inheritdoc}
537
   */
538
  public function getCacheMaxAge() {
539
    return $this->pluginDefinition['schema_cache_max_age'];
540
  }
541
}
542