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

FieldPluginBase::resolve()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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