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

FieldPluginBase::unwrapResult()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 11
nc 3
nop 2
dl 0
loc 17
rs 8.2222
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 $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
87
  }
88
89
  /**
90
   * {@inheritdoc}
91
   */
92
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveContext $context, ResolveInfo $info) {
93
    $result = $callback($value, $args, $context, $info);
94
95
    if (is_callable($result)) {
96
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
97
        return $this->resolveDeferred($result, $value, $args, $context, $info);
98
      });
99
    }
100
101
    // Set the context language to the current language parameter.
102
    LanguageNegotiationGraphQL::setCurrentLanguage($context->getContext('language', $info));
103
104
    // Extract the result array.
105
    try {
106
      $result = iterator_to_array($result);
107
    }
108
    catch (\Exception $exc) {
109
      throw $exc;
110
    }
111
    finally {
112
      // In any case, set the language context back to null.
113
      LanguageNegotiationGraphQL::unsetCurrentLanguage();
114
    }
115
116
    // Only collect cache metadata if this is a query. All other operation types
117
    // are not cacheable anyways.
118
    if ($info->operation->operation === 'query') {
119
      $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
120
      foreach ($dependencies as $dependency) {
121
        $context->addCacheableDependency($dependency);
122
      }
123
    }
124
125
    return $this->unwrapResult($result, $info);
126
  }
127
128
  /**
129
   * Unwrap the resolved values.
130
   *
131
   * @param array $result
132
   *   The resolved values.
133
   * @param \GraphQL\Type\Definition\ResolveInfo $info
134
   *   The resolve info object.
135
   *
136
   * @return mixed
137
   *   The extracted values (an array of values in case this is a list, an
138
   *   arbitrary value if it isn't).
139
   */
140
  protected function unwrapResult($result, ResolveInfo $info) {
141
    $result = array_map(function ($item) {
142
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
143
    }, $result);
144
145
    $result = array_map(function ($item) {
146
      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...
147
    }, $result);
148
149
    // If this is a list, return the result as an array.
150
    $type = $info->returnType;
151
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
152
      return $result;
153
    }
154
155
    return !empty($result) ? reset($result) : NULL;
156
  }
157
158
  /**
159
   * Retrieve the list of cache dependencies for a given value and arguments.
160
   *
161
   * @param array $result
162
   *   The result of the field.
163
   * @param mixed $parent
164
   *   The parent value.
165
   * @param array $args
166
   *   The arguments passed to the field.
167
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
168
   *   The resolve context.
169
   * @param \GraphQL\Type\Definition\ResolveInfo $info
170
   *   The resolve info object.
171
   *
172
   * @return array
173
   *   A list of cacheable dependencies.
174
   */
175
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
176
    $self = new CacheableMetadata();
177
    $definition = $this->getPluginDefinition();
178
    if (!empty($definition['response_cache_contexts'])) {
179
      $self->addCacheContexts($definition['response_cache_contexts']);
180
    }
181
182
    if (!empty($definition['response_cache_tags'])) {
183
      $self->addCacheTags($definition['response_cache_tags']);
184
    }
185
186
    if (isset($definition['response_cache_max_age'])) {
187
      $self->mergeCacheMaxAge($definition['response_cache_max_age']);
188
    }
189
190
    return array_merge([$self], array_filter($result, function ($item) {
191
      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...
192
    }));
193
  }
194
195
  /**
196
   * Retrieve the list of field values.
197
   *
198
   * Always returns a list of field values. Even for single value fields.
199
   * Single/multi field handling is responsibility of the base class.
200
   *
201
   * @param mixed $value
202
   *   The current object value.
203
   * @param array $args
204
   *   Field arguments.
205
   * @param $context
206
   *   The resolve context.
207
   * @param \GraphQL\Type\Definition\ResolveInfo $info
208
   *   The resolve info object.
209
   *
210
   * @return \Generator
211
   *   The value generator.
212
   */
213
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
214
    // Allow overriding this class without having to declare this method.
215
    yield NULL;
216
  }
217
218
}
219