Completed
Pull Request — 8.x-3.x (#525)
by Sebastian
02:16
created

FieldPluginBase::resolveDeferred()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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