Completed
Push — 8.x-3.x ( 22ac55...94c6a1 )
by Philipp
33:33 queued 22:29
created

EntityQueryEntities::resolveEntities()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 21

Duplication

Lines 6
Ratio 28.57 %

Importance

Changes 0
Metric Value
cc 7
nc 7
nop 5
dl 6
loc 21
rs 8.6506
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Fields\EntityQuery;
4
5
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
6
use Drupal\Core\Entity\ContentEntityInterface;
7
use Drupal\Core\Entity\EntityInterface;
8
use Drupal\Core\Entity\EntityRepositoryInterface;
9
use Drupal\Core\Entity\EntityTypeManagerInterface;
10
use Drupal\Core\Entity\Query\QueryInterface;
11
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
12
use Drupal\Core\TypedData\TranslatableInterface;
13
use Drupal\graphql\GraphQL\Buffers\EntityBuffer;
14
use Drupal\graphql\GraphQL\Cache\CacheableValue;
15
use Drupal\graphql\GraphQL\Execution\ResolveContext;
16
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
use GraphQL\Type\Definition\ResolveInfo;
19
20
/**
21
 * Retrieve the entity result set of an entity query.
22
 *
23
 * @GraphQLField(
24
 *   id = "entity_query_entities",
25
 *   secure = true,
26
 *   name = "entities",
27
 *   type = "[Entity]",
28
 *   parents = {"EntityQueryResult"},
29
 *   arguments = {
30
 *     "language" = "LanguageId"
31
 *   },
32
 *   contextual_arguments = {"language"}
33
 * )
34
 */
35
class EntityQueryEntities extends FieldPluginBase implements ContainerFactoryPluginInterface {
36
  use DependencySerializationTrait;
37
38
  /**
39
   * The entity buffer service.
40
   *
41
   * @var \Drupal\graphql\GraphQL\Buffers\EntityBuffer
42
   */
43
  protected $entityBuffer;
44
45
  /**
46
   * The entity type manager service.
47
   *
48
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
49
   */
50
  protected $entityTypeManager;
51
52
  /**
53
   * The entity repository service.
54
   *
55
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
56
   */
57
  protected $entityRepository;
58
59
  /**
60
   * {@inheritdoc}
61
   */
62 View Code Duplication
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
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...
63
    return new static(
64
      $configuration,
65
      $pluginId,
66
      $pluginDefinition,
67
      $container->get('entity_type.manager'),
68
      $container->get('entity.repository'),
69
      $container->get('graphql.buffer.entity')
70
    );
71
  }
72
73
  /**
74
   * EntityQueryEntities constructor.
75
   *
76
   * @param array $configuration
77
   *   The plugin configuration array.
78
   * @param string $pluginId
79
   *   The plugin id.
80
   * @param mixed $pluginDefinition
81
   *   The plugin definition array.
82
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
83
   *   The entity type manager service.
84
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
85
   *   The entity repository service.
86
   * @param \Drupal\graphql\GraphQL\Buffers\EntityBuffer $entityBuffer
87
   *   The entity buffer service.
88
   */
89 View Code Duplication
  public function __construct(
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...
90
    array $configuration,
91
    $pluginId,
92
    $pluginDefinition,
93
    EntityTypeManagerInterface $entityTypeManager,
94
    EntityRepositoryInterface $entityRepository,
95
    EntityBuffer $entityBuffer
96
  ) {
97
    parent::__construct($configuration, $pluginId, $pluginDefinition);
98
    $this->entityTypeManager = $entityTypeManager;
99
    $this->entityRepository = $entityRepository;
100
    $this->entityBuffer = $entityBuffer;
101
  }
102
103
  /**
104
   * {@inheritdoc}
105
   */
106
  public function resolveValues($value, array $args, ResolveContext $context, ResolveInfo $info) {
107
    if ($value instanceof QueryInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\Query\QueryInterface 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...
108
      $type = $value->getEntityTypeId();
109
      $result = $value->execute();
110
      $metadata = $value->getMetaData('graphql_context');
111
112
      if ($value->hasTag('revisions')) {
113
        return $this->resolveFromRevisionIds($type, array_keys($result), $metadata, $args, $context, $info);
114
      }
115
116
      // If this is a revision query, the version ids are the array keys.
117
      return $this->resolveFromEntityIds($type, array_values($result), $metadata, $args, $context, $info);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->resolveFro...args, $context, $info); (Closure) is incompatible with the return type of the parent method Drupal\graphql\Plugin\Gr...uginBase::resolveValues of type Generator.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
118
    }
119
  }
120
121
  /**
122
   * Resolves entities lazily through the entity buffer.
123
   *
124
   * @param string $type
125
   *   The entity type.
126
   * @param array $ids
127
   *   The entity ids to load.
128
   * @param mixed $metadata
129
   *   The query context.
130
   * @param array $args
131
   *   The field arguments array.
132
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
133
   *   The resolve context.
134
   * @param \GraphQL\Type\Definition\ResolveInfo $info
135
   *   The resolve info object.
136
   *
137
   * @return \Closure
138
   *   The deferred resolver.
139
   */
140
  protected function resolveFromEntityIds($type, $ids, $metadata, array $args, ResolveContext $context, ResolveInfo $info) {
141
    $resolve = $this->entityBuffer->add($type, $ids);
142
    return function($value, array $args, ResolveContext $context, ResolveInfo $info) use ($resolve, $metadata) {
143
      return $this->resolveEntities($resolve(), $metadata, $args,  $context, $info);
144
    };
145
  }
146
147
  /**
148
   * Resolves entity revisions.
149
   *
150
   * @param string $type
151
   *   The entity type.
152
   * @param array $ids
153
   *   The entity revision ids to load.
154
   * @param mixed $metadata
155
   *   The query context.
156
   * @param array $args
157
   *   The field arguments array.
158
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
159
   *   The resolve context.
160
   * @param \GraphQL\Type\Definition\ResolveInfo $info
161
   *   The resolve info object.
162
   *
163
   * @return \Generator
164
   *   The resolved revisions.
165
   */
166
  protected function resolveFromRevisionIds($type, $ids, $metadata, array $args, ResolveContext $context, ResolveInfo $info) {
167
    $storage = $this->entityTypeManager->getStorage($type);
168
    $entities = array_map(function ($id) use ($storage) {
169
      return $storage->loadRevision($id);
170
    }, $ids);
171
172
    return $this->resolveEntities($entities, $metadata, $args, $context, $info);
173
  }
174
175
  /**
176
   * Resolves entity objects and checks view permissions.
177
   *
178
   * @param array $entities
179
   *   The entities to resolve.
180
   * @param mixed $metadata
181
   *   The query context.
182
   * @param array $args
183
   *   The field arguments array.
184
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
185
   *   The resolve context.
186
   * @param \GraphQL\Type\Definition\ResolveInfo $info
187
   *   The resolve info object.
188
   *
189
   * @return \Generator
190
   *   The resolved entities.
191
   */
192
  protected function resolveEntities(array $entities, $metadata, array $args, ResolveContext $context, ResolveInfo $info) {
193
    $language = $this->negotiateLanguage($metadata, $args, $context, $info);
194
195
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
196
    foreach ($entities as $entity) {
197
      // Translate the entity if it is translatable and a language was given.
198
      if ($language && $entity instanceof TranslatableInterface && $entity->isTranslatable()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $language of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Bug introduced by
The class Drupal\Core\TypedData\TranslatableInterface 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...
199
        if ($entity->hasTranslation($language)) {
200
          $entity = $entity->getTranslation($language);
201
        }
202
      }
203
204
      $access = $entity->access('view', NULL, TRUE);
205 View Code Duplication
      if ($access->isAllowed()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
206
        yield $entity->addCacheableDependency($access);
207
      }
208
      else {
209
        yield new CacheableValue(NULL, [$access]);
210
      }
211
    }
212
  }
213
214
  /**
215
   * Negotiate the language for the resolved entities.
216
   *
217
   * @param mixed $metadata
218
   *   The query context.
219
   * @param array $args
220
   *   The field arguments array.
221
   * @param \Drupal\graphql\GraphQL\Execution\ResolveContext $context
222
   *   The resolve context.
223
   * @param \GraphQL\Type\Definition\ResolveInfo $info
224
   *   The resolve info object.
225
   *
226
   * @return string|null
227
   *   The negotiated language id.
228
   */
229
  protected function negotiateLanguage($metadata, $args, ResolveContext $context, ResolveInfo $info) {
230
    if (!empty($args['language'])) {
231
      return $args['language'];
232
    }
233
234
    if (isset($metadata['parent']) && ($parent = $metadata['parent']) && $parent instanceof EntityInterface) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\EntityInterface 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...
235
      return $parent->language()->getId();
236
    }
237
238
    return NULL;
239
  }
240
241
}
242