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

RouteEntity::resolveEntityTranslation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 4
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Fields\Routing;
4
5
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
6
use Drupal\Core\Entity\EntityInterface;
7
use Drupal\Core\Entity\EntityRepositoryInterface;
8
use Drupal\Core\Entity\EntityTypeManagerInterface;
9
use Drupal\Core\Language\Language;
10
use Drupal\Core\Language\LanguageManagerInterface;
11
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
12
use Drupal\Core\TypedData\TranslatableInterface;
13
use Drupal\Core\Url;
14
use Drupal\graphql\GraphQL\Buffers\SubRequestBuffer;
15
use Drupal\graphql\GraphQL\Cache\CacheableValue;
16
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
use Youshido\GraphQL\Execution\ResolveInfo;
19
20
/**
21
 * Retrieve the current routes entity, if it is an entity route.
22
 *
23
 * @GraphQLField(
24
 *   id = "route_entity",
25
 *   secure = true,
26
 *   name = "entity",
27
 *   description = @Translation("The entity belonging to the current url."),
28
 *   parents = {"EntityCanonicalUrl"},
29
 *   type = "Entity"
30
 * )
31
 */
32
class RouteEntity 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...
33
  use DependencySerializationTrait;
34
35
  /**
36
   * The entity type manager.
37
   *
38
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
39
   */
40
  protected $entityTypeManager;
41
42
  /**
43
   * The language manager.
44
   *
45
   * @var \Drupal\Core\Language\LanguageManagerInterface
46
   */
47
  protected $languageManager;
48
49
  /**
50
   * The sub-request buffer service.
51
   *
52
   * @var \Drupal\graphql\GraphQL\Buffers\SubRequestBuffer
53
   */
54
  protected $subrequestBuffer;
55
56
  /**
57
   * The entity repository service.
58
   *
59
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
60
   */
61
  protected $entityRepository;
62
63
  /**
64
   * {@inheritdoc}
65
   */
66 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...
67
    return new static(
68
      $configuration,
69
      $pluginId,
70
      $pluginDefinition,
71
      $container->get('entity_type.manager'),
72
      $container->get('entity.repository'),
73
      $container->get('language_manager'),
74
      $container->get('graphql.buffer.subrequest')
75
    );
76
  }
77
78
  /**
79
   * RouteEntity constructor.
80
   *
81
   * @param array $configuration
82
   *   The plugin configuration array.
83
   * @param string $pluginId
84
   *   The plugin id.
85
   * @param mixed $pluginDefinition
86
   *   The plugin definition array.
87
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
88
   *   The entity type manager service.
89
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
90
   *   The entity repository service.
91
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
92
   *   The language manager service.
93
   * @param \Drupal\graphql\GraphQL\Buffers\SubRequestBuffer $subrequestBuffer
94
   */
95 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...
96
    array $configuration,
97
    $pluginId,
98
    $pluginDefinition,
99
    EntityTypeManagerInterface $entityTypeManager,
100
    EntityRepositoryInterface $entityRepository,
101
    LanguageManagerInterface $languageManager,
102
    SubRequestBuffer $subrequestBuffer
103
  ) {
104
    parent::__construct($configuration, $pluginId, $pluginDefinition);
105
    $this->entityTypeManager = $entityTypeManager;
106
    $this->languageManager = $languageManager;
107
    $this->subrequestBuffer = $subrequestBuffer;
108
    $this->entityRepository = $entityRepository;
109
  }
110
111
  /**
112
   * {@inheritdoc}
113
   */
114
  public function resolveValues($value, array $args, ResolveInfo $info) {
115
    if ($value instanceof Url) {
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Url 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
      list(, $type) = explode('.', $value->getRouteName());
117
      $parameters = $value->getRouteParameters();
118
      $storage = $this->entityTypeManager->getStorage($type);
119
120
      if (!$entity = $storage->load($parameters[$type])) {
121
        return $this->resolveMissingEntity($value, $args, $info);
122
      }
123
124
      if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
0 ignored issues
show
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...
125
        return $this->resolveEntityTranslation($entity, $value, $args, $info);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->resolveEnt... $value, $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...
126
      }
127
128
      return $this->resolveEntity($entity, $value, $args, $info);
129
    }
130
  }
131
132
  /**
133
   * @param \Drupal\Core\Entity\EntityInterface $entity
134
   *   The entity to resolve.
135
   * @param \Drupal\Core\Url $url
136
   *   The url of the entity to resolve.
137
   * @param array $args
138
   *   The field arguments array.
139
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
140
   *   The resolve info object.
141
   *
142
   * @return \Generator
143
   */
144
  protected function resolveEntity(EntityInterface $entity, Url $url, array $args, ResolveInfo $info) {
145
    $access = $entity->access('view', NULL, TRUE);
146 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...
147
      yield $entity->addCacheableDependency($access);
148
    }
149
    else {
150
      yield new CacheableValue(NULL, [$access]);
151
    }
152
  }
153
154
  /**
155
   * Resolves the entity translation from the given url context.
156
   *
157
   * @param \Drupal\Core\Entity\EntityInterface $entity
158
   *   The entity to resolve.
159
   * @param \Drupal\Core\Url $url
160
   *   The url of the entity to resolve.
161
   * @param array $args
162
   *   The field arguments array.
163
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
164
   *   The resolve info object.
165
   *
166
   * @return \Closure
167
   */
168
  protected function resolveEntityTranslation(EntityInterface $entity, Url $url, array $args, ResolveInfo $info) {
169
    $resolve = $this->subrequestBuffer->add($url, function () {
170
      return $this->languageManager->getCurrentLanguage(Language::TYPE_CONTENT)->getId();
171
    });
172
173
    return function ($value, array $args, ResolveInfo $info) use ($resolve, $entity) {
174
      $language = $resolve();
175
      $entity = $this->entityRepository->getTranslationFromContext($entity, $language);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $entity, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
176
      return $this->resolveEntity($entity, $value, $args, $info);
177
    };
178
  }
179
180
  /**
181
   * m
182
   *
183
   * @param \Drupal\Core\Url $url
184
   *   The url of the entity to resolve.
185
   * @param array $args
186
   *   The field arguments array.
187
   * @param \Youshido\GraphQL\Execution\ResolveInfo $info
188
   *   The resolve info object.
189
   *
190
   * @return \Generator
191
   */
192
  protected function resolveMissingEntity(Url $url, $args, $info) {
193
    yield (new CacheableValue(NULL))->addCacheTags(['4xx-response']);
194
  }
195
}
196
197