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

EntityById::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 4
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\GraphQL\Fields\Entity;
4
5
use Drupal\Core\Cache\CacheableMetadata;
6
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
7
use Drupal\Core\Entity\EntityRepositoryInterface;
8
use Drupal\Core\Entity\EntityTypeManagerInterface;
9
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
10
use Drupal\graphql\GraphQL\Buffers\EntityBuffer;
11
use Drupal\graphql\GraphQL\Cache\CacheableValue;
12
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Youshido\GraphQL\Execution\ResolveInfo;
15
16
/**
17
 * Retrieve an entity by its id.
18
 *
19
 * @GraphQLField(
20
 *   id = "entity_by_id",
21
 *   secure = true,
22
 *   name = "entityById",
23
 *   weight = -1,
24
 *   arguments = {
25
 *     "id" = "String!"
26
 *   },
27
 *   deriver = "Drupal\graphql_core\Plugin\Deriver\Fields\EntityByIdDeriver"
28
 * )
29
 */
30
class EntityById 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...
31
  use DependencySerializationTrait;
32
33
  /**
34
   * The entity buffer service.
35
   *
36
   * @var \Drupal\graphql\GraphQL\Buffers\EntityBuffer
37
   */
38
  protected $entityBuffer;
39
40
  /**
41
   * The entity type manager service.
42
   *
43
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
44
   */
45
  protected $entityTypeManager;
46
47
  /**
48
   * The entity repository service.
49
   *
50
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
51
   */
52
  protected $entityRepository;
53
54
  /**
55
   * {@inheritdoc}
56
   */
57
  public function __construct(
58
    array $configuration,
59
    $pluginId,
60
    $pluginDefinition,
61
    EntityTypeManagerInterface $entityTypeManager,
62
    EntityRepositoryInterface $entityRepository,
63
    EntityBuffer $entityBuffer
64
  ) {
65
    parent::__construct($configuration, $pluginId, $pluginDefinition);
66
    $this->entityBuffer = $entityBuffer;
67
    $this->entityTypeManager = $entityTypeManager;
68
    $this->entityRepository = $entityRepository;
69
  }
70
71
  /**
72
   * {@inheritdoc}
73
   */
74
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
75
    return new static(
76
      $configuration,
77
      $pluginId,
78
      $pluginDefinition,
79
      $container->get('entity_type.manager'),
80
      $container->get('entity.repository'),
81
      $container->get('graphql.buffer.entity')
82
    );
83
  }
84
85
  /**
86
   * {@inheritdoc}
87
   */
88
  protected function resolveValues($value, array $args, ResolveInfo $info) {
89
    $resolver = $this->entityBuffer->add($this->getPluginDefinition()['entity_type'], $args['id']);
90
    return function ($value, array $args, ResolveInfo $info) use ($resolver) {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return function ($value,...ntity : NULL); } }; (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...
91
      if (!$entity = $resolver()) {
92
        // If there is no entity with this id, add the list cache tags so that the
93
        // cache entry is purged whenever a new entity of this type is saved.
94
        $pluginDefinition = $this->getPluginDefinition();
95
        $entityType = $this->entityTypeManager->getDefinition($pluginDefinition['entity_type']);
96
97
        // Add the list cache tags to the processor's cache collector.
98
        $this->commitCacheTags($info, $entityType->getListCacheTags());
99
100
        yield NULL;
101
      }
102
      else {
103
        /** @var \Drupal\Core\Entity\EntityInterface $entity */
104
        if (($access = $entity->access('view', NULL, TRUE)) && ($allowed = $access->isAllowed())) {
105
          if (isset($args['language']) && $args['language'] != $entity->language()->getId()) {
106
            $entity = $this->entityRepository->getTranslationFromContext($entity, $args['language']);
107
          }
108
        }
109
110
        $this->commitCacheableDependency($info, $access);
111
        yield !empty($allowed) ? $entity : NULL;
112
      }
113
    };
114
  }
115
116
}
117