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

FieldPluginBase::resolve()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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