Completed
Pull Request — 8.x-3.x (#550)
by Philipp
02:10
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\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
    $definition = $this->getPluginDefinition();
68
69
    // If not resolving in a trusted environment, check if the field is secure.
70
    if (!$context->getGlobal('development', FALSE) && !$context->getGlobal('bypass field security', FALSE)) {
71
      if (empty($definition['secure'])) {
72
        throw new \Exception(sprintf("Unable to resolve insecure field '%s'.", $info->fieldName));
73
      }
74
    }
75
76
    foreach ($definition['contextual_arguments'] as $argument) {
77
      if (array_key_exists($argument, $args) && !is_null($args[$argument])) {
78
        $context->setContext($argument, $args[$argument], $info);
79
      }
80
      else {
81
        $args[$argument] = $context->getContext($argument, $info);
82
      }
83
    }
84
85
    return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
86
  }
87
88
  /**
89
   * {@inheritdoc}
90
   */
91
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveContext $context, ResolveInfo $info) {
92
    $result = $callback($value, $args, $context, $info);
93
    if (is_callable($result)) {
94
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
95
        return $this->resolveDeferred($result, $value, $args, $context, $info);
96
      });
97
    }
98
99
    // Extract the result array.
100
    $result = iterator_to_array($result);
101
102
    // Only collect cache metadata if this is a query. All other operation types
103
    // are not cacheable anyways.
104
    if ($info->operation->operation === 'query') {
105
      $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
106
      foreach ($dependencies as $dependency) {
107
        $context->addCacheableDependency($dependency);
108
      }
109
    }
110
111
    return $this->unwrapResult($result, $info);
112
  }
113
114
  /**
115
   * Unwrap the resolved values.
116
   *
117
   * @param array $result
118
   *   The resolved values.
119
   * @param \GraphQL\Type\Definition\ResolveInfo $info
120
   *   The resolve info object.
121
   *
122
   * @return mixed
123
   *   The extracted values (an array of values in case this is a list, an
124
   *   arbitrary value if it isn't).
125
   */
126
  protected function unwrapResult($result, ResolveInfo $info) {
127
    $result = array_map(function ($item) {
128
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
129
    }, $result);
130
131
    $result = array_map(function ($item) {
132
      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...
133
    }, $result);
134
135
    // If this is a list, return the result as an array.
136
    $type = $info->returnType;
137
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
138
      return $result;
139
    }
140
141
    return !empty($result) ? reset($result) : NULL;
142
  }
143
144
  /**
145
   * Retrieve the list of cache dependencies for a given value and arguments.
146
   *
147
   * @param array $result
148
   *   The result of the field.
149
   * @param mixed $parent
150
   *   The parent value.
151
   * @param array $args
152
   *   The arguments passed to the field.
153
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
154
   *   The resolve context.
155
   * @param \GraphQL\Type\Definition\ResolveInfo $info
156
   *   The resolve info object.
157
   *
158
   * @return array
159
   *   A list of cacheable dependencies.
160
   */
161
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
162
    $self = new CacheableMetadata();
163
    $definition = $this->getPluginDefinition();
164
    if (!empty($definition['response_cache_contexts'])) {
165
      $self->addCacheContexts($definition['response_cache_contexts']);
166
    }
167
168
    if (!empty($definition['response_cache_tags'])) {
169
      $self->addCacheTags($definition['response_cache_tags']);
170
    }
171
172
    if (isset($definition['response_cache_max_age'])) {
173
      $self->mergeCacheMaxAge($definition['response_cache_max_age']);
174
    }
175
176
    return array_merge([$self], array_filter($result, function ($item) {
177
      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...
178
    }));
179
  }
180
181
  /**
182
   * Retrieve the list of field values.
183
   *
184
   * Always returns a list of field values. Even for single value fields.
185
   * Single/multi field handling is responsibility of the base class.
186
   *
187
   * @param mixed $value
188
   *   The current object value.
189
   * @param array $args
190
   *   Field arguments.
191
   * @param $context
192
   *   The resolve context.
193
   * @param \GraphQL\Type\Definition\ResolveInfo $info
194
   *   The resolve info object.
195
   *
196
   * @return \Generator
197
   *   The value generator.
198
   */
199
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
200
    // Allow overriding this class without having to declare this method.
201
    yield NULL;
202
  }
203
204
}
205