Completed
Push — 8.x-3.x ( 6608c9...0ba9eb )
by Philipp
02:38
created

SchemaPluginBase::getServer()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 1
nop 0
dl 0
loc 42
rs 9.248
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\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 validateSchema() {
215
    return NULL;
216
  }
217
218
  /**
219
   * {@inheritdoc}
220
   */
221
  public function getServer() {
222
    // If the current user has appropriate permissions, allow to bypass
223
    // the secure fields restriction.
224
    $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...
225
226
    // Create the server config.
227
    $config = ServerConfig::create();
228
229
    // Each document (e.g. in a batch query) gets its own resolve context. This
230
    // allows us to collect the cache metadata and contextual values (e.g.
231
    // inheritance for language) for each query separately.
232
    $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...
233
      // Each document (e.g. in a batch query) gets its own resolve context. This
234
      // allows us to collect the cache metadata and contextual values (e.g.
235
      // inheritance for language) for each query separately.
236
      $context = new ResolveContext($globals);
237
      $context->addCacheTags(['graphql_response']);
238
      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...
239
        $context->addCacheableDependency($this);
240
      }
241
242
      return $context;
243
    });
244
245
    $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...
246
      if (isset($params->queryId)) {
247
        // Assume that pre-parsed documents are already validated. This allows
248
        // us to store pre-validated query documents e.g. for persisted queries
249
        // effectively improving performance by skipping run-time validation.
250
        return [];
251
      }
252
253
      return array_values(DocumentValidator::defaultRules());
254
    });
255
256
    $config->setPersistentQueryLoader([$this->queryProvider, 'getQuery']);
257
    $config->setQueryBatching(TRUE);
258
    $config->setDebug(!!$this->parameters['development']);
259
    $config->setSchema($this->getSchema());
260
261
    return $config;
262
  }
263
264
  /**
265
  /**
266
   * {@inheritdoc}
267
   */
268
  public function hasFields($type) {
269
    return isset($this->pluginDefinition['field_association_map'][$type]);
270
  }
271
272
  /**
273
   * {@inheritdoc}
274
   */
275
  public function hasMutations() {
276
    return !empty($this->pluginDefinition['mutation_map']);
277
  }
278
279
  /**
280
   * {@inheritdoc}
281
   */
282
  public function hasSubscriptions() {
283
    return !empty($this->pluginDefinition['subscription_map']);
284
  }
285
286
  /**
287
   * {@inheritdoc}
288
   */
289
  public function hasType($name) {
290
    return isset($this->pluginDefinition['type_map'][$name]);
291
  }
292
293
  /**
294
   * {@inheritdoc}
295
   */
296
  public function getFields($type) {
297
    $association = $this->pluginDefinition['field_association_map'];
298
    $fields = $this->pluginDefinition['field_map'];
299
300
    if (isset($association[$type])) {
301
      return $this->processFields(array_map(function ($id) use ($fields) {
302
        return $fields[$id];
303
      }, $association[$type]));
304
    }
305
306
    return [];
307
  }
308
309
  /**
310
   * {@inheritdoc}
311
   */
312
  public function getMutations() {
313
    return $this->processMutations($this->pluginDefinition['mutation_map']);
314
  }
315
316
  /**
317
   * {@inheritdoc}
318
   */
319
  public function getSubscriptions() {
320
    return $this->processSubscriptions($this->pluginDefinition['subscription_map']);
321
  }
322
323
  /**
324
   * {@inheritdoc}
325
   */
326
  public function getTypes() {
327
    return array_map(function ($name) {
328
      return $this->getType($name);
329
    }, array_keys($this->pluginDefinition['type_map']));
330
  }
331
332
  /**
333
   * {@inheritdoc}
334
   */
335
  public function getSubTypes($name) {
336
    $association = $this->pluginDefinition['type_association_map'];
337
    return isset($association[$name]) ? $association[$name] : [];
338
  }
339
340
  /**
341
   * {@inheritdoc}
342
   */
343
  public function resolveType($name, $value, ResolveContext $context, ResolveInfo $info) {
344
    $association = $this->pluginDefinition['type_association_map'];
345
    $types = $this->pluginDefinition['type_map'];
346
    if (!isset($association[$name])) {
347
      return NULL;
348
    }
349
350
    foreach ($association[$name] as $type) {
351
      // TODO: Try to avoid loading the type for the check. Consider to make it static!
352
      if (isset($types[$type]) && $instance = $this->buildType($types[$type])) {
353
        if ($instance->isTypeOf($value, $context, $info)) {
354
          return $instance;
355
        }
356
      }
357
    }
358
359
    return NULL;
360
  }
361
362
  /**
363
   * {@inheritdoc}
364
   */
365
  public function getType($name) {
366
    $types = $this->pluginDefinition['type_map'];
367
    $references = $this->pluginDefinition['type_reference_map'];
368
    if (isset($types[$name])) {
369
      return $this->buildType($this->pluginDefinition['type_map'][$name]);
370
    }
371
372
    do {
373
      if (isset($references[$name])) {
374
        return $this->buildType($types[$references[$name]]);
375
      }
376
    } while (($pos = strpos($name, ':')) !== FALSE && $name = substr($name, 0, $pos));
377
378
    throw new \LogicException(sprintf('Missing type %s.', $name));
379
  }
380
381
  /**
382
   * {@inheritdoc}
383
   */
384
  public function processMutations($mutations) {
385
    return array_map([$this, 'buildMutation'], $mutations);
386
  }
387
388
  /**
389
   * {@inheritdoc}
390
   */
391
  public function processSubscriptions($subscriptions) {
392
    return array_map([$this, 'buildSubscription'], $subscriptions);
393
  }
394
395
  /**
396
   * {@inheritdoc}
397
   */
398
  public function processFields($fields) {
399
    return array_map([$this, 'buildField'], $fields);
400
  }
401
402
  /**
403
   * {@inheritdoc}
404
   */
405
  public function processArguments($args) {
406
    return array_map(function ($arg) {
407
      return [
408
        'type' => $this->processType($arg['type']),
409
      ] + $arg;
410
    }, $args);
411
  }
412
413
  /**
414
   * {@inheritdoc}
415
   */
416
  public function processType($type) {
417
    list($type, $decorators) = $type;
418
419
    return array_reduce($decorators, function ($type, $decorator) {
420
      return $decorator($type);
421
    }, $this->getType($type));
422
  }
423
424
  /**
425
   * Retrieves the type instance for the given reference.
426
   *
427
   * @param array $type
428
   *   The type reference.
429
   *
430
   * @return \GraphQL\Type\Definition\Type
431
   *   The type instance.
432
   */
433
  protected function buildType($type) {
434
    if (!isset($this->types[$type['id']])) {
435
      $creator = [$type['class'], 'createInstance'];
436
      $manager = $this->typeManagers->getTypeManager($type['type']);
437
      $this->types[$type['id']] = $creator($this, $manager, $type['definition'], $type['id']);
438
    }
439
440
    return $this->types[$type['id']];
441
  }
442
443
  /**
444
   * Retrieves the field definition for a given field reference.
445
   *
446
   * @param array $field
447
   *   The type reference.
448
   *
449
   * @return array
450
   *   The field definition.
451
   */
452 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...
453
    if (!isset($this->fields[$field['id']])) {
454
      $creator = [$field['class'], 'createInstance'];
455
      $this->fields[$field['id']] = $creator($this, $this->fieldManager, $field['definition'], $field['id']);
456
    }
457
458
    return $this->fields[$field['id']];
459
  }
460
461
  /**
462
   * Retrieves the mutation definition for a given field reference.
463
   *
464
   * @param array $mutation
465
   *   The mutation reference.
466
   *
467
   * @return array
468
   *   The mutation definition.
469
   */
470 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...
471
    if (!isset($this->mutations[$mutation['id']])) {
472
      $creator = [$mutation['class'], 'createInstance'];
473
      $this->mutations[$mutation['id']] = $creator($this, $this->mutationManager, $mutation['definition'], $mutation['id']);
474
    }
475
476
    return $this->mutations[$mutation['id']];
477
  }
478
479
  /**
480
   * Retrieves the subscription definition for a given field reference.
481
   *
482
   * @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...
483
   *   The subscription reference.
484
   *
485
   * @return array
486
   *   The subscription definition.
487
   */
488 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...
489
    if (!isset($this->subscriptions[$subscription['id']])) {
490
      $creator = [$subscription['class'], 'createInstance'];
491
      $this->subscriptions[$subscription['id']] = $creator($this, $this->subscriptionManager, $subscription['definition'], $subscription['id']);
492
    }
493
494
    return $this->subscriptions[$subscription['id']];
495
  }
496
497
  /**
498
   * {@inheritdoc}
499
   */
500
  public function getCacheContexts() {
501
    return [];
502
  }
503
504
  /**
505
   * {@inheritdoc}
506
   */
507
  public function getCacheTags() {
508
    return $this->pluginDefinition['schema_cache_tags'];
509
  }
510
511
  /**
512
   * {@inheritdoc}
513
   */
514
  public function getCacheMaxAge() {
515
    return $this->pluginDefinition['schema_cache_max_age'];
516
  }
517
}
518