Completed
Pull Request — 8.x-3.x (#653)
by Sebastian
05:18 queued 02:30
created

SchemaPluginBase::allowsQueryBatching()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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