Completed
Pull Request — 8.x-3.x (#497)
by Sebastian
05:09
created

FieldPluginBase::resolveDeferred()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 5
nop 4
dl 0
loc 23
rs 8.5906
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\Core\Cache\RefinableCacheableDependencyInterface;
8
use Drupal\graphql\GraphQL\Field\Field;
9
use Drupal\graphql\GraphQL\SecureFieldInterface;
10
use Drupal\graphql\GraphQL\ValueWrapperInterface;
11
use Drupal\graphql\Plugin\GraphQL\PluggableSchemaBuilderInterface;
12
use Drupal\graphql\Plugin\GraphQL\Traits\ArgumentAwarePluginTrait;
13
use Drupal\graphql\Plugin\GraphQL\Traits\CacheablePluginTrait;
14
use Drupal\graphql\Plugin\GraphQL\Traits\NamedPluginTrait;
15
use Drupal\graphql\Plugin\GraphQL\TypeSystemPluginInterface;
16
use Youshido\GraphQL\Exception\ResolveException;
17
use Youshido\GraphQL\Execution\DeferredResolver;
18
use Youshido\GraphQL\Execution\ResolveInfo;
19
use Youshido\GraphQL\Type\ListType\ListType;
20
21
/**
22
 * Base class for field plugins.
23
 */
24
abstract class FieldPluginBase extends PluginBase implements TypeSystemPluginInterface, SecureFieldInterface {
25
  use CacheablePluginTrait;
26
  use NamedPluginTrait;
27
  use ArgumentAwarePluginTrait;
28
29
  /**
30
   * The field instance.
31
   *
32
   * @var \Drupal\graphql\GraphQL\Field\Field
33
   */
34
  protected $definition;
35
36
  /**
37
   * {@inheritdoc}
38
   */
39 View Code Duplication
  public function getDefinition(PluggableSchemaBuilderInterface $schemaBuilder) {
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...
40
    if (!isset($this->definition)) {
41
      $definition = $this->getPluginDefinition();
42
43
      $config = [
44
        'name' => $this->buildName(),
45
        'description' => $this->buildDescription(),
46
        'type' => $this->buildType($schemaBuilder),
47
        'args' => $this->buildArguments($schemaBuilder),
48
        'isDeprecated' => !empty($definition['deprecated']),
49
        'deprecationReason' => !empty($definition['deprecated']) ? !empty($definition['deprecated']) : '',
50
      ];
51
52
      $this->definition = new Field($this, $schemaBuilder, $config);
53
    }
54
55
    return $this->definition;
56
  }
57
58
  /**
59
   * {@inheritdoc}
60
   */
61
  public function isSecure() {
62
    return isset($this->getPluginDefinition()['secure']) && $this->getPluginDefinition()['secure'];
63
  }
64
65
  /**
66
   * {@inheritdoc}
67
   */
68
  public function resolve($value, array $args, ResolveInfo $info) {
69
    // If not resolving in a trusted environment, check if the field is secure.
70
    $container = $info->getExecutionContext()->getContainer();
71
    if ($container->has('secure') && !$container->get('secure') && !$this->isSecure()) {
72
      throw new ResolveException(sprintf("Unable to resolve insecure field '%s' (%s).", $info->getField()->getName(), get_class($this)));
73
    }
74
75
    return $this->resolveDeferred([$this, 'resolveValues'], $value, $args, $info);
76
  }
77
78
  /**
79
   * {@inheritdoc}
80
   */
81
  protected function resolveDeferred(callable $callback, $value, array $args, ResolveInfo $info) {
82
    $result = $callback($value, $args, $info);
83
    if (is_callable($result)) {
84
      return new DeferredResolver(function () use ($result, $args, $info, $value) {
85
        return $this->resolveDeferred($result, $value, $args, $info);
86
      });
87
    }
88
89
    // Extract the result array.
90
    $result = iterator_to_array($result);
91
92
    // Commit the cache dependencies into the processor's cache collector.
93
    if ($dependencies = $this->getCacheDependencies($result, $value, $args, $info)) {
94
      $container = $info->getExecutionContext()->getContainer();
95
      if ($container->has('metadata') && $metadata = $container->get('metadata')) {
96
        if ($metadata instanceof RefinableCacheableDependencyInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Cache\Refina...ableDependencyInterface 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...
97
          array_walk($dependencies, [$metadata, 'addCacheableDependency']);
98
        }
99
      }
100
    }
101
102
    return $this->unwrapResult($result, $info);
103
  }
104
105
  /**
106
   * @param $result
107
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
108
   *
109
   * @return array|mixed|null
110
   */
111
  protected function unwrapResult($result, ResolveInfo $info) {
112
    $result = array_map(function ($item) {
113
      return $item instanceof ValueWrapperInterface ? $item->getValue() : $item;
114
    }, $result);
115
116
    // If this is a list, return the result as an array.
117
    $type = $info->getReturnType()->getNullableType();
118
    if ($type instanceof ListType) {
119
      return $result;
120
    }
121
122
    return !empty($result) ? reset($result) : NULL;
123
  }
124
125
  /**
126
   * Retrieve the list of cache dependencies for a given value and arguments.
127
   *
128
   * @param array $result
129
   *   The result of the field.
130
   * @param mixed $parent
131
   *   The parent value.
132
   * @param array $args
133
   *   The arguments passed to the field.
134
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
135
   *   The resolve info object.
136
   *
137
   * @return array
138
   *   A list of cacheable dependencies.
139
   */
140
  protected function getCacheDependencies(array $result, $parent, array $args, ResolveInfo $info) {
141
    return array_filter($result, function ($item) {
142
      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...
143
    });
144
  }
145
146
  /**
147
   * Retrieve the list of field values.
148
   *
149
   * Always returns a list of field values. Even for single value fields.
150
   * Single/multi field handling is responsibility of the base class.
151
   *
152
   * @param mixed $value
153
   *   The current object value.
154
   * @param array $args
155
   *   Field arguments.
156
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
157
   *   The resolve info object.
158
   *
159
   * @return \Generator
160
   *   The value generator.
161
   */
162
  protected function resolveValues($value, array $args, ResolveInfo $info) {
163
    // Allow overriding this class without having to declare this method.
164
    yield NULL;
165
  }
166
167
}
168