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

FieldPluginBase   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 9
dl 0
loc 137
rs 10
c 0
b 0
f 0

7 Methods

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