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

FieldPluginBase::unwrapResult()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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