Completed
Push — 8.x-3.x ( 8ae1c4...42317c )
by Sebastian
04:13 queued 02:03
created

FieldPluginBase::getCacheDependencies()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 8
nop 5
dl 0
loc 19
rs 9.2
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\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
    $result = $this->getRenderer()->executeInRenderContext(new RenderContext(), function () use ($callback, $value, $args, $context, $info) {
156
      return $callback($value, $args, $context, $info);
157
    });
158
159
    if (is_callable($result)) {
160
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
161
        return $this->resolveDeferred($result, $value, $args, $context, $info);
162
      });
163
    }
164
165
    $result = iterator_to_array($result);
166
167
    // Only collect cache metadata if this is a query. All other operation types
168
    // are not cacheable anyways.
169
    if ($info->operation->operation === 'query') {
170
      $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
171
      foreach ($dependencies as $dependency) {
172
        $context->addCacheableDependency($dependency);
173
      }
174
    }
175
176
    return $this->unwrapResult($result, $info);
177
  }
178
179
  /**
180
   * Unwrap the resolved values.
181
   *
182
   * @param array $result
183
   *   The resolved values.
184
   * @param \GraphQL\Type\Definition\ResolveInfo $info
185
   *   The resolve info object.
186
   *
187
   * @return mixed
188
   *   The extracted values (an array of values in case this is a list, an
189
   *   arbitrary value if it isn't).
190
   */
191
  protected function unwrapResult($result, ResolveInfo $info) {
192
    $result = array_map(function ($item) {
193
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
194
    }, $result);
195
196
    $result = array_map(function ($item) {
197
      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...
198
    }, $result);
199
200
    // If this is a list, return the result as an array.
201
    $type = $info->returnType;
202
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
203
      return $result;
204
    }
205
206
    return !empty($result) ? reset($result) : NULL;
207
  }
208
209
  /**
210
   * Retrieve the list of cache dependencies for a given value and arguments.
211
   *
212
   * @param array $result
213
   *   The result of the field.
214
   * @param mixed $parent
215
   *   The parent value.
216
   * @param array $args
217
   *   The arguments passed to the field.
218
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
219
   *   The resolve context.
220
   * @param \GraphQL\Type\Definition\ResolveInfo $info
221
   *   The resolve info object.
222
   *
223
   * @return array
224
   *   A list of cacheable dependencies.
225
   */
226
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
227
    $self = new CacheableMetadata();
228
    $definition = $this->getPluginDefinition();
229
    if (!empty($definition['response_cache_contexts'])) {
230
      $self->addCacheContexts($definition['response_cache_contexts']);
231
    }
232
233
    if (!empty($definition['response_cache_tags'])) {
234
      $self->addCacheTags($definition['response_cache_tags']);
235
    }
236
237
    if (isset($definition['response_cache_max_age'])) {
238
      $self->mergeCacheMaxAge($definition['response_cache_max_age']);
239
    }
240
241
    return array_merge([$self], array_filter($result, function ($item) {
242
      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...
243
    }));
244
  }
245
246
  /**
247
   * Retrieve the list of field values.
248
   *
249
   * Always returns a list of field values. Even for single value fields.
250
   * Single/multi field handling is responsibility of the base class.
251
   *
252
   * @param mixed $value
253
   *   The current object value.
254
   * @param array $args
255
   *   Field arguments.
256
   * @param $context
257
   *   The resolve context.
258
   * @param \GraphQL\Type\Definition\ResolveInfo $info
259
   *   The resolve info object.
260
   *
261
   * @return \Generator
262
   *   The value generator.
263
   */
264
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
265
    // Allow overriding this class without having to declare this method.
266
    yield NULL;
267
  }
268
269
}
270