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

FieldPluginBase::getDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 10
loc 10
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\Core\Cache\CacheableDependencyInterface;
7
use Drupal\graphql\GraphQL\Execution\ResolveContext;
8
use Drupal\graphql\GraphQL\ValueWrapperInterface;
9
use Drupal\graphql\Plugin\FieldPluginInterface;
10
use Drupal\graphql\Plugin\FieldPluginManager;
11
use Drupal\graphql\Plugin\SchemaBuilder;
12
use Drupal\graphql\Plugin\GraphQL\Traits\ArgumentAwarePluginTrait;
13
use Drupal\graphql\Plugin\GraphQL\Traits\CacheablePluginTrait;
14
use Drupal\graphql\Plugin\GraphQL\Traits\DeprecatablePluginTrait;
15
use Drupal\graphql\Plugin\GraphQL\Traits\DescribablePluginTrait;
16
use Drupal\graphql\Plugin\GraphQL\Traits\TypedPluginTrait;
17
use GraphQL\Deferred;
18
use GraphQL\Type\Definition\ListOfType;
19
use GraphQL\Type\Definition\NonNull;
20
use GraphQL\Type\Definition\ResolveInfo;
21
22
abstract class FieldPluginBase extends PluginBase implements FieldPluginInterface {
23
  use CacheablePluginTrait;
24
  use DescribablePluginTrait;
25
  use TypedPluginTrait;
26
  use ArgumentAwarePluginTrait;
27
  use DeprecatablePluginTrait;
28
29
  /**
30
   * {@inheritdoc}
31
   */
32
  public static function createInstance(SchemaBuilder $builder, FieldPluginManager $manager, $definition, $id) {
33
    return [
34
      'description' => $definition['description'],
35
      'deprecationReason' => $definition['deprecationReason'],
36
      'type' => $builder->processType($definition['type']),
37
      'args' => $builder->processArguments($definition['args']),
38
      'resolve' => function ($value, array $args, ResolveContext $context, ResolveInfo $info) use ($manager, $id) {
39
        $instance = $manager->getInstance(['id' => $id]);
40
        return $instance->resolve($value, $args, $context, $info);
41
      },
42
    ];
43
  }
44
45
  /**
46
   * {@inheritdoc}
47
   */
48 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...
49
    $definition = $this->getPluginDefinition();
50
51
    return [
52
      'type' => $this->buildType($definition),
53
      'description' => $this->buildDescription($definition),
54
      'args' => $this->buildArguments($definition),
55
      'deprecationReason' => $this->buildDeprecationReason($definition),
56
    ] + $this->buildCacheMetadata($definition);
57
  }
58
59
  /**
60
   * {@inheritdoc}
61
   */
62
  public function resolve($value, array $args, ResolveContext $context, ResolveInfo $info) {
63
    // If not resolving in a trusted environment, check if the field is secure.
64
    if (!$context->getGlobal('development', FALSE)) {
65
      $definition = $this->getPluginDefinition();
66
      if (empty($definition['secure'])) {
67
        throw new \Exception(sprintf("Unable to resolve insecure field '%s'.", $info->fieldName));
68
      }
69
    }
70
71
    return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $context, $info);
72
  }
73
74
  /**
75
   * {@inheritdoc}
76
   */
77
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveContext $context, ResolveInfo $info) {
78
    $result = $callback($value, $args, $context, $info);
79
    if (is_callable($result)) {
80
      return new Deferred(function () use ($result, $value, $args, $context, $info) {
81
        return $this->resolveDeferred($result, $value, $args, $context, $info);
82
      });
83
    }
84
85
    // Extract the result array.
86
    $result = iterator_to_array($result);
87
    $dependencies = $this->getCacheDependencies($result, $value, $args, $context, $info);
88
    foreach ($dependencies as $dependency) {
89
      $context->addCacheableDependency($dependency);
90
    }
91
92
    return $this->unwrapResult($result, $info);
93
  }
94
95
  /**
96
   * Unwrap the resolved values.
97
   *
98
   * @param array $result
99
   *   The resolved values.
100
   * @param \GraphQL\Type\Definition\ResolveInfo $info
101
   *   The resolve info object.
102
   *
103
   * @return mixed
104
   *   The extracted values (an array of values in case this is a list, an
105
   *   arbitrary value if it isn't).
106
   */
107
  protected function unwrapResult($result, ResolveInfo $info) {
108
    $result = array_map(function ($item) {
109
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
110
    }, $result);
111
112
    // If this is a list, return the result as an array.
113
    $type = $info->returnType;
114
    if ($type instanceof ListOfType || ($type instanceof NonNull && $type->getWrappedType() instanceof ListOfType)) {
115
      return $result;
116
    }
117
118
    return !empty($result) ? reset($result) : NULL;
119
  }
120
121
  /**
122
   * Retrieve the list of cache dependencies for a given value and arguments.
123
   *
124
   * @param array $result
125
   *   The result of the field.
126
   * @param mixed $parent
127
   *   The parent value.
128
   * @param array $args
129
   *   The arguments passed to the field.
130
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
131
   *   The resolve context.
132
   * @param \GraphQL\Type\Definition\ResolveInfo $info
133
   *   The resolve info object.
134
   *
135
   * @return array A list of cacheable dependencies.
136
   * A list of cacheable dependencies.
137
   */
138
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveContext $context, ResolveInfo $info) {
139
    return array_filter($result, function ($item) {
140
      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...
141
    });
142
  }
143
144
  /**
145
   * Retrieve the list of field values.
146
   *
147
   * Always returns a list of field values. Even for single value fields.
148
   * Single/multi field handling is responsibility of the base class.
149
   *
150
   * @param mixed $value
151
   *   The current object value.
152
   * @param array $args
153
   *   Field arguments.
154
   * @param $context
155
   *   The resolve context.
156
   * @param \GraphQL\Type\Definition\ResolveInfo $info
157
   *   The resolve info object.
158
   *
159
   * @return \Generator
160
   *   The value generator.
161
   */
162
  protected function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
163
    // Allow overriding this class without having to declare this method.
164
    yield NULL;
165
  }
166
167
}
168