Completed
Pull Request — 8.x-3.x (#525)
by Philipp
08:20
created

FieldPluginBase   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 171
Duplicated Lines 6.43 %

Coupling/Cohesion

Components 2
Dependencies 12

Importance

Changes 0
Metric Value
dl 11
loc 171
rs 10
c 0
b 0
f 0
wmc 22
lcom 2
cbo 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A createInstance() 0 13 1
A getDefinition() 11 11 1
A resolve() 0 11 4
B resolveDeferred() 0 22 4
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\graphql\GraphQL\Execution\ResolveContext;
10
use Drupal\graphql\GraphQL\ValueWrapperInterface;
11
use Drupal\graphql\Plugin\FieldPluginInterface;
12
use Drupal\graphql\Plugin\FieldPluginManager;
13
use Drupal\graphql\Plugin\GraphQL\Traits\ArgumentAwarePluginTrait;
14
use Drupal\graphql\Plugin\GraphQL\Traits\CacheablePluginTrait;
15
use Drupal\graphql\Plugin\GraphQL\Traits\DeprecatablePluginTrait;
16
use Drupal\graphql\Plugin\GraphQL\Traits\DescribablePluginTrait;
17
use Drupal\graphql\Plugin\GraphQL\Traits\TypedPluginTrait;
18
use Drupal\graphql\Plugin\SchemaBuilderInterface;
19
use GraphQL\Deferred;
20
use GraphQL\Type\Definition\ListOfType;
21
use GraphQL\Type\Definition\NonNull;
22
use GraphQL\Type\Definition\ResolveInfo;
23
24
abstract class FieldPluginBase extends PluginBase implements FieldPluginInterface {
25
  use CacheablePluginTrait;
26
  use DescribablePluginTrait;
27
  use TypedPluginTrait;
28
  use ArgumentAwarePluginTrait;
29
  use DeprecatablePluginTrait;
30
31
  /**
32
   * {@inheritdoc}
33
   */
34
  public static function createInstance(SchemaBuilderInterface $builder, FieldPluginManager $manager, $definition, $id) {
35
    return [
36
      'description' => $definition['description'],
37
      'contexts' => $definition['contexts'],
38
      'deprecationReason' => $definition['deprecationReason'],
39
      'type' => $builder->processType($definition['type']),
40
      'args' => $builder->processArguments($definition['args']),
41
      'resolve' => function ($value, array $args, ResolveContext $context, ResolveInfo $info) use ($manager, $id) {
42
        $instance = $manager->getInstance(['id' => $id]);
43
        return $instance->resolve($value, $args, $context, $info);
44
      },
45
    ];
46
  }
47
48
  /**
49
   * {@inheritdoc}
50
   */
51 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...
52
    $definition = $this->getPluginDefinition();
53
54
    return [
55
      'type' => $this->buildType($definition),
56
      'description' => $this->buildDescription($definition),
57
      'args' => $this->buildArguments($definition),
58
      'deprecationReason' => $this->buildDeprecationReason($definition),
59
      'contexts' => $this->buildCacheContexts($definition),
60
    ];
61
  }
62
63
  /**
64
   * {@inheritdoc}
65
   */
66
  public function resolve($value, array $args, ResolveContext $context, ResolveInfo $info) {
67
    // If not resolving in a trusted environment, check if the field is secure.
68
    if (!$context->getGlobal('development', FALSE) && !$context->getGlobal('bypass field security', FALSE)) {
69
      $definition = $this->getPluginDefinition();
70
      if (empty($definition['secure'])) {
71
        throw new \Exception(sprintf("Unable to resolve insecure field '%s'.", $info->fieldName));
72
      }
73
    }
74
75
    return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
76
  }
77
78
  /**
79
   * {@inheritdoc}
80
   */
81
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveContext $context, ResolveInfo $info) {
82
    $result = $callback($value, $args, $context, $info);
83
    if (is_callable($result)) {
84
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
85
        return $this->resolveDeferred($result, $value, $args, $context, $info);
86
      });
87
    }
88
89
    // Extract the result array.
90
    $result = iterator_to_array($result);
91
92
    // Only collect cache metadata if this is a query. All other operation types
93
    // are not cacheable anyways.
94
    if ($info->operation->operation === 'query') {
95
      $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
96
      foreach ($dependencies as $dependency) {
97
        $context->addCacheableDependency($dependency);
98
      }
99
    }
100
101
    return $this->unwrapResult($result, $info);
102
  }
103
104
  /**
105
   * Unwrap the resolved values.
106
   *
107
   * @param array $result
108
   *   The resolved values.
109
   * @param \GraphQL\Type\Definition\ResolveInfo $info
110
   *   The resolve info object.
111
   *
112
   * @return mixed
113
   *   The extracted values (an array of values in case this is a list, an
114
   *   arbitrary value if it isn't).
115
   */
116
  protected function unwrapResult($result, ResolveInfo $info) {
117
    $result = array_map(function ($item) {
118
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
119
    }, $result);
120
121
    $result = array_map(function ($item) {
122
      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...
123
    }, $result);
124
125
    // If this is a list, return the result as an array.
126
    $type = $info->returnType;
127
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
128
      return $result;
129
    }
130
131
    return !empty($result) ? reset($result) : NULL;
132
  }
133
134
  /**
135
   * Retrieve the list of cache dependencies for a given value and arguments.
136
   *
137
   * @param array $result
138
   *   The result of the field.
139
   * @param mixed $parent
140
   *   The parent value.
141
   * @param array $args
142
   *   The arguments passed to the field.
143
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
144
   *   The resolve context.
145
   * @param \GraphQL\Type\Definition\ResolveInfo $info
146
   *   The resolve info object.
147
   *
148
   * @return array
149
   *   A list of cacheable dependencies.
150
   */
151
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
152
    $self = new CacheableMetadata();
153
    $definition = $this->getPluginDefinition();
154
    if (!empty($definition['response_cache_contexts'])) {
155
      $self->addCacheContexts($definition['response_cache_contexts']);
156
    }
157
158
    if (!empty($definition['response_cache_tags'])) {
159
      $self->addCacheTags($definition['response_cache_tags']);
160
    }
161
162
    if (isset($definition['response_cache_max_age'])) {
163
      $self->mergeCacheMaxAge($definition['response_cache_max_age']);
164
    }
165
166
    return array_merge([$self], array_filter($result, function ($item) {
167
      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...
168
    }));
169
  }
170
171
  /**
172
   * Retrieve the list of field values.
173
   *
174
   * Always returns a list of field values. Even for single value fields.
175
   * Single/multi field handling is responsibility of the base class.
176
   *
177
   * @param mixed $value
178
   *   The current object value.
179
   * @param array $args
180
   *   Field arguments.
181
   * @param $context
182
   *   The resolve context.
183
   * @param \GraphQL\Type\Definition\ResolveInfo $info
184
   *   The resolve info object.
185
   *
186
   * @return \Generator
187
   *   The value generator.
188
   */
189
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
190
    // Allow overriding this class without having to declare this method.
191
    yield NULL;
192
  }
193
194
}
195