Completed
Pull Request — 8.x-3.x (#588)
by Philipp
02:17
created

FieldPluginBase   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 252
Duplicated Lines 4.37 %

Coupling/Cohesion

Components 2
Dependencies 13

Importance

Changes 0
Metric Value
dl 11
loc 252
rs 9.2
c 0
b 0
f 0
wmc 34
lcom 2
cbo 13

10 Methods

Rating   Name   Duplication   Size   Complexity  
A createInstance() 0 13 1
A getLanguageContext() 0 6 2
A getRenderer() 0 6 2
A getDefinition() 11 11 1
C resolve() 0 29 8
A isLanguageAwareField() 0 5 1
C resolveDeferred() 0 32 7
B unwrapResult() 0 17 7
A getCacheDependencies() 0 19 4
A resolveValues() 0 4 1

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace Drupal\graphql\Plugin\GraphQL\Fields;
4
5
use Drupal\Component\Plugin\PluginBase;
6
use Drupal\Component\Render\MarkupInterface;
7
use Drupal\Core\Cache\CacheableDependencyInterface;
8
use Drupal\Core\Cache\CacheableMetadata;
9
use Drupal\Core\Render\RenderContext;
10
use Drupal\graphql\GraphQL\Execution\ResolveContext;
11
use Drupal\graphql\GraphQL\ValueWrapperInterface;
12
use Drupal\graphql\Plugin\FieldPluginInterface;
13
use Drupal\graphql\Plugin\FieldPluginManager;
14
use Drupal\graphql\Plugin\GraphQL\Traits\ArgumentAwarePluginTrait;
15
use Drupal\graphql\Plugin\GraphQL\Traits\CacheablePluginTrait;
16
use Drupal\graphql\Plugin\GraphQL\Traits\DeprecatablePluginTrait;
17
use Drupal\graphql\Plugin\GraphQL\Traits\DescribablePluginTrait;
18
use Drupal\graphql\Plugin\GraphQL\Traits\TypedPluginTrait;
19
use Drupal\graphql\Plugin\LanguageNegotiation\LanguageNegotiationGraphQL;
20
use Drupal\graphql\Plugin\SchemaBuilderInterface;
21
use GraphQL\Deferred;
22
use GraphQL\Type\Definition\ListOfType;
23
use GraphQL\Type\Definition\NonNull;
24
use GraphQL\Type\Definition\ResolveInfo;
25
26
abstract class FieldPluginBase extends PluginBase implements FieldPluginInterface {
27
  use CacheablePluginTrait;
28
  use DescribablePluginTrait;
29
  use TypedPluginTrait;
30
  use ArgumentAwarePluginTrait;
31
  use DeprecatablePluginTrait;
32
33
  /**
34
   * The language context service.
35
   *
36
   * @var \Drupal\graphql\GraphQLLanguageContext
37
   */
38
  protected $languageContext;
39
40
  /**
41
   * The renderer service.
42
   *
43
   * @var \Drupal\Core\Render\RendererInterface
44
   */
45
  protected $renderer;
46
47
  /**
48
   * {@inheritdoc}
49
   */
50
  public static function createInstance(SchemaBuilderInterface $builder, FieldPluginManager $manager, $definition, $id) {
51
    return [
52
      'description' => $definition['description'],
53
      'contexts' => $definition['contexts'],
54
      'deprecationReason' => $definition['deprecationReason'],
55
      'type' => $builder->processType($definition['type']),
56
      'args' => $builder->processArguments($definition['args']),
57
      'resolve' => function ($value, array $args, ResolveContext $context, ResolveInfo $info) use ($manager, $id) {
58
        $instance = $manager->getInstance(['id' => $id]);
59
        return $instance->resolve($value, $args, $context, $info);
60
      },
61
    ];
62
  }
63
64
  /**
65
   * Get the language context instance.
66
   *
67
   * @return \Drupal\graphql\GraphQLLanguageContext
68
   *   The language context service.
69
   */
70
  protected function getLanguageContext() {
71
    if (!isset($this->languageContext)) {
72
      $this->languageContext = \Drupal::service('graphql.language_context');
73
    }
74
    return $this->languageContext;
75
  }
76
77
  /**
78
   * Get the renderer service.
79
   *
80
   * @return \Drupal\Core\Render\RendererInterface
81
   */
82
  protected function getRenderer() {
83
    if (!isset($this->renderer)) {
84
      $this->renderer = \Drupal::service('renderer');
85
    }
86
    return $this->renderer;
87
  }
88
89
  /**
90
   * {@inheritdoc}
91
   */
92 View Code Duplication
  public function getDefinition() {
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...
93
    $definition = $this->getPluginDefinition();
94
95
    return [
96
      'type' => $this->buildType($definition),
97
      'description' => $this->buildDescription($definition),
98
      'args' => $this->buildArguments($definition),
99
      'deprecationReason' => $this->buildDeprecationReason($definition),
100
      'contexts' => $this->buildCacheContexts($definition),
101
    ];
102
  }
103
104
  /**
105
   * {@inheritdoc}
106
   */
107
  public function resolve($value, array $args, ResolveContext $context, ResolveInfo $info) {
108
    $definition = $this->getPluginDefinition();
109
110
    // If not resolving in a trusted environment, check if the field is secure.
111
    if (!$context->getGlobal('development', FALSE) && !$context->getGlobal('bypass field security', FALSE)) {
112
      if (empty($definition['secure'])) {
113
        throw new \Exception(sprintf("Unable to resolve insecure field '%s'.", $info->fieldName));
114
      }
115
    }
116
117
    foreach ($definition['contextual_arguments'] as $argument) {
118
      if (array_key_exists($argument, $args) && !is_null($args[$argument])) {
119
        $context->setContext($argument, $args[$argument], $info);
120
      }
121
      else {
122
        $args[$argument] = $context->getContext($argument, $info);
123
      }
124
    }
125
126
    if ($this->isLanguageAwareField()) {
127
      return $this->getLanguageContext()
128
        ->executeInLanguageContext(function () use ($value, $args, $context, $info) {
129
          return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
130
        }, $context->getContext('language', $info));
131
    }
132
    else {
133
      return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
134
    }
135
  }
136
137
  /**
138
   * Indicator if the field is language aware.
139
   *
140
   * Checks for 'languages:*' cache contexts on the fields definition.
141
   *
142
   * @return bool
143
   *   The fields language awareness status.
144
   */
145
  protected function isLanguageAwareField() {
146
    return (boolean) count(array_filter($this->getPluginDefinition()['response_cache_contexts'], function ($context) {
147
      return strpos($context, 'languages:') === 0;
148
    }));
149
  }
150
151
  /**
152
   * {@inheritdoc}
153
   */
154
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveContext $context, ResolveInfo $info) {
155
    $renderContext = new RenderContext();
156
157
    $result = $this->getRenderer()->executeInRenderContext($renderContext, function () use ($callback, $value, $args, $context, $info) {
158
      $result = $callback($value, $args, $context, $info);
159
      if ($result instanceof \Generator) {
160
        $result = iterator_to_array($result);
161
      }
162
      return $result;
163
    });
164
165
    if (!$renderContext->isEmpty() && $info->operation->operation === 'query') {
166
      $context->addCacheableDependency($renderContext->pop());
167
    }
168
169
    if (is_callable($result)) {
170
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
171
        return $this->resolveDeferred($result, $value, $args, $context, $info);
172
      });
173
    }
174
175
    // Only collect cache metadata if this is a query. All other operation types
176
    // are not cacheable anyways.
177
    if ($info->operation->operation === 'query') {
178
      $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
179
      foreach ($dependencies as $dependency) {
180
        $context->addCacheableDependency($dependency);
181
      }
182
    }
183
184
    return $this->unwrapResult($result, $info);
185
  }
186
187
  /**
188
   * Unwrap the resolved values.
189
   *
190
   * @param array $result
191
   *   The resolved values.
192
   * @param \GraphQL\Type\Definition\ResolveInfo $info
193
   *   The resolve info object.
194
   *
195
   * @return mixed
196
   *   The extracted values (an array of values in case this is a list, an
197
   *   arbitrary value if it isn't).
198
   */
199
  protected function unwrapResult($result, ResolveInfo $info) {
200
    $result = array_map(function ($item) {
201
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
202
    }, $result);
203
204
    $result = array_map(function ($item) {
205
      return $item instanceof MarkupInterface ? $item->__toString() : $item;
0 ignored issues
show
Bug introduced by
The class Drupal\Component\Render\MarkupInterface 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...
206
    }, $result);
207
208
    // If this is a list, return the result as an array.
209
    $type = $info->returnType;
210
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
211
      return $result;
212
    }
213
214
    return !empty($result) ? reset($result) : NULL;
215
  }
216
217
  /**
218
   * Retrieve the list of cache dependencies for a given value and arguments.
219
   *
220
   * @param array $result
221
   *   The result of the field.
222
   * @param mixed $parent
223
   *   The parent value.
224
   * @param array $args
225
   *   The arguments passed to the field.
226
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
227
   *   The resolve context.
228
   * @param \GraphQL\Type\Definition\ResolveInfo $info
229
   *   The resolve info object.
230
   *
231
   * @return array
232
   *   A list of cacheable dependencies.
233
   */
234
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
235
    $self = new CacheableMetadata();
236
    $definition = $this->getPluginDefinition();
237
    if (!empty($definition['response_cache_contexts'])) {
238
      $self->addCacheContexts($definition['response_cache_contexts']);
239
    }
240
241
    if (!empty($definition['response_cache_tags'])) {
242
      $self->addCacheTags($definition['response_cache_tags']);
243
    }
244
245
    if (isset($definition['response_cache_max_age'])) {
246
      $self->mergeCacheMaxAge($definition['response_cache_max_age']);
247
    }
248
249
    return array_merge([$self], array_filter($result, function ($item) {
250
      return $item 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...
251
    }));
252
  }
253
254
  /**
255
   * Retrieve the list of field values.
256
   *
257
   * Always returns a list of field values. Even for single value fields.
258
   * Single/multi field handling is responsibility of the base class.
259
   *
260
   * @param mixed $value
261
   *   The current object value.
262
   * @param array $args
263
   *   Field arguments.
264
   * @param $context
265
   *   The resolve context.
266
   * @param \GraphQL\Type\Definition\ResolveInfo $info
267
   *   The resolve info object.
268
   *
269
   * @return \Generator
270
   *   The value generator.
271
   */
272
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
273
    // Allow overriding this class without having to declare this method.
274
    yield NULL;
275
  }
276
277
}
278