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

FieldPluginBase::resolve()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 7
nop 4
dl 0
loc 24
rs 6.7272
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\Language\LanguageManagerInterface;
10
use Drupal\graphql\GraphQL\Execution\ResolveContext;
11
use Drupal\graphql\GraphQL\ValueWrapperInterface;
12
use Drupal\graphql\GraphQLLanguageContext;
13
use Drupal\graphql\Plugin\FieldPluginInterface;
14
use Drupal\graphql\Plugin\FieldPluginManager;
15
use Drupal\graphql\Plugin\GraphQL\Traits\ArgumentAwarePluginTrait;
16
use Drupal\graphql\Plugin\GraphQL\Traits\CacheablePluginTrait;
17
use Drupal\graphql\Plugin\GraphQL\Traits\DeprecatablePluginTrait;
18
use Drupal\graphql\Plugin\GraphQL\Traits\DescribablePluginTrait;
19
use Drupal\graphql\Plugin\GraphQL\Traits\TypedPluginTrait;
20
use Drupal\graphql\Plugin\LanguageNegotiation\LanguageNegotiationGraphQL;
21
use Drupal\graphql\Plugin\SchemaBuilderInterface;
22
use GraphQL\Deferred;
23
use GraphQL\Type\Definition\ListOfType;
24
use GraphQL\Type\Definition\NonNull;
25
use GraphQL\Type\Definition\ResolveInfo;
26
27
abstract class FieldPluginBase extends PluginBase implements FieldPluginInterface {
28
  use CacheablePluginTrait;
29
  use DescribablePluginTrait;
30
  use TypedPluginTrait;
31
  use ArgumentAwarePluginTrait;
32
  use DeprecatablePluginTrait;
33
34
  /**
35
   * The language context, for simulating active languages in fields.
36
   *
37
   * @var \Drupal\graphql\GraphQLLanguageContext
38
   */
39
  protected $languageContext;
40
41
  /**
42
   * Set the language context instance.
43
   *
44
   * @param \Drupal\graphql\GraphQLLanguageContext $languageContext
45
   *   The language context instance.
46
   */
47
  public function setLanguageContext(GraphQLLanguageContext $languageContext) {
48
    $this->languageContext = $languageContext;
49
  }
50
51
  /**
52
   * {@inheritdoc}
53
   */
54
  public static function createInstance(SchemaBuilderInterface $builder, FieldPluginManager $manager, $definition, $id) {
55
    return [
56
      'description' => $definition['description'],
57
      'contexts' => $definition['contexts'],
58
      'deprecationReason' => $definition['deprecationReason'],
59
      'type' => $builder->processType($definition['type']),
60
      'args' => $builder->processArguments($definition['args']),
61
      'resolve' => function ($value, array $args, ResolveContext $context, ResolveInfo $info) use ($manager, $id) {
62
        $instance = $manager->getInstance(['id' => $id]);
63
        return $instance->resolve($value, $args, $context, $info);
0 ignored issues
show
Bug introduced by
The method resolve does only exist in Drupal\graphql\Plugin\Gr...\Fields\FieldPluginBase, but not in Drupal\graphql\Plugin\FieldPluginInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

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