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

FieldPluginBase::getLanguageContext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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