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