Completed
Pull Request — 8.x-3.x (#517)
by Sebastian
07:28 queued 02:24
created

EntityQueryEntities::resolveEntities()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 6
Ratio 31.58 %

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 5
nop 4
dl 6
loc 19
rs 8.8571
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\Plugin\GraphQL\Fields\FieldPluginBase;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Youshido\GraphQL\Execution\ResolveInfo;
18
19
/**
20
 * Retrieve the entity result set of an entity query.
21
 *
22
 * @GraphQLField(
23
 *   id = "entity_query_entities",
24
 *   secure = true,
25
 *   name = "entities",
26
 *   type = "[Entity]",
27
 *   parents = {"EntityQueryResult"},
28
 *   arguments = {
29
 *     "language" = "LanguageId"
30
 *   }
31
 * )
32
 */
33
class EntityQueryEntities extends FieldPluginBase implements ContainerFactoryPluginInterface {
0 ignored issues
show
Bug introduced by
There is one abstract method getPluginDefinition in this class; you could implement it, or declare this class as abstract.
Loading history...
34
  use DependencySerializationTrait;
35
36
  /**
37
   * The entity buffer service.
38
   *
39
   * @var \Drupal\graphql\GraphQL\Buffers\EntityBuffer
40
   */
41
  protected $entityBuffer;
42
43
  /**
44
   * The entity type manager service.
45
   *
46
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
47
   */
48
  protected $entityTypeManager;
49
50
  /**
51
   * The entity repository service.
52
   *
53
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
54
   */
55
  protected $entityRepository;
56
57
  /**
58
   * {@inheritdoc}
59
   */
60 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...
61
    return new static(
62
      $configuration,
63
      $pluginId,
64
      $pluginDefinition,
65
      $container->get('entity_type.manager'),
66
      $container->get('entity.repository'),
67
      $container->get('graphql.buffer.entity')
68
    );
69
  }
70
71
  /**
72
   * EntityQueryEntities constructor.
73
   *
74
   * @param array $configuration
75
   *   The plugin configuration array.
76
   * @param string $pluginId
77
   *   The plugin id.
78
   * @param mixed $pluginDefinition
79
   *   The plugin definition array.
80
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
81
   *   The entity type manager service.
82
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
83
   *   The entity repository service.
84
   * @param \Drupal\graphql\GraphQL\Buffers\EntityBuffer $entityBuffer
85
   *   The entity buffer service.
86
   */
87 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...
88
    array $configuration,
89
    $pluginId,
90
    $pluginDefinition,
91
    EntityTypeManagerInterface $entityTypeManager,
92
    EntityRepositoryInterface $entityRepository,
93
    EntityBuffer $entityBuffer
94
  ) {
95
    parent::__construct($configuration, $pluginId, $pluginDefinition);
96
    $this->entityTypeManager = $entityTypeManager;
97
    $this->entityRepository = $entityRepository;
98
    $this->entityBuffer = $entityBuffer;
99
  }
100
101
  /**
102
   * {@inheritdoc}
103
   */
104
  public function resolveValues($value, array $args, ResolveInfo $info) {
105
    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...
106
      $type = $value->getEntityTypeId();
107
      $result = $value->execute();
108
      $context = $value->getMetaData('graphql_context');
109
110
      if ($value->hasTag('revisions')) {
111
        return $this->resolveFromRevisionIds($type, array_keys($result), $context, $args, $info);
112
      }
113
114
      // If this is a revision query, the version ids are the array keys.
115
      return $this->resolveFromEntityIds($type, array_values($result), $context, $args, $info);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->resolveFro...context, $args, $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...
116
    }
117
  }
118
119
  /**
120
   * Resolves entities lazily through the entity buffer.
121
   *
122
   * @param string $type
123
   *   The entity type.
124
   * @param array $ids
125
   *   The entity ids to load.
126
   * @param mixed $context
127
   *   The query context.
128
   * @param array $args
129
   *   The field arguments array.
130
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
131
   *   The resolve info object.
132
   *
133
   * @return \Closure
134
   *   The deferred resolver.
135
   */
136
  protected function resolveFromEntityIds($type, $ids, $context, array $args, ResolveInfo $info) {
137
    $resolve = $this->entityBuffer->add($type, $ids);
138
    return function($value, array $args, ResolveInfo $info) use ($resolve, $context) {
139
      return $this->resolveEntities($resolve(), $context, $args, $info);
140
    };
141
  }
142
143
  /**
144
   * Resolves entity revisions.
145
   *
146
   * @param string $type
147
   *   The entity type.
148
   * @param array $ids
149
   *   The entity revision ids to load.
150
   * @param mixed $context
151
   *   The query context.
152
   * @param array $args
153
   *   The field arguments array.
154
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
155
   *   The resolve info object.
156
   *
157
   * @return \Generator
158
   *   The resolved revisions.
159
   */
160
  protected function resolveFromRevisionIds($type, $ids, $context, array $args, ResolveInfo $info) {
161
    $storage = $this->entityTypeManager->getStorage($type);
162
    $entities = array_map(function ($id) use ($storage) {
163
      return $storage->loadRevision($id);
164
    }, $ids);
165
166
    return $this->resolveEntities($entities, $context, $args, $info);
167
  }
168
169
  /**
170
   * Resolves entity objects and checks view permissions.
171
   *
172
   * @param array $entities
173
   *   The entities to resolve.
174
   * @param mixed $context
175
   *   The query context.
176
   * @param array $args
177
   *   The field arguments array.
178
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
179
   *   The resolve info object.
180
   *
181
   * @return \Generator
182
   *   The resolved entities.
183
   */
184
  protected function resolveEntities(array $entities, $context, array $args, ResolveInfo $info) {
185
    $language = $this->negotiateLanguage($context, $args, $info);
186
187
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
188
    foreach ($entities as $entity) {
189
      // Translate the entity if it is translatable and a language was given.
190
      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...
191
        $entity = $this->entityRepository->getTranslationFromContext($entity, $language);
192
      }
193
194
      $access = $entity->access('view', NULL, TRUE);
195 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...
196
        yield $entity->addCacheableDependency($access);
197
      }
198
      else {
199
        yield new CacheableValue(NULL, [$access]);
200
      }
201
    }
202
  }
203
204
  /**
205
   * Negotiate the language for the resolved entities.
206
   *
207
   * @param mixed $context
208
   *   The query context.
209
   * @param array $args
210
   *   The field arguments array.
211
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
212
   *   The resolve info object.
213
   *
214
   * @return string|null
215
   *   The negotiated language id.
216
   */
217
  protected function negotiateLanguage($context, $args, ResolveInfo $info) {
218
    if (!empty($args['language'])) {
219
      return $args['language'];
220
    }
221
222
    if (isset($context['parent']) && ($parent = $context['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...
223
      return $parent->language()->getId();
224
    }
225
226
    return NULL;
227
  }
228
229
}
230