Completed
Pull Request — 8.x-3.x (#477)
by Sebastian
02:08
created

EntityByIdDeriver::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql_core\Plugin\Deriver\Fields;
4
5
use Drupal\Component\Plugin\Derivative\DeriverBase;
6
use Drupal\Core\Entity\ContentEntityTypeInterface;
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
9
use Drupal\Core\StringTranslation\StringTranslationTrait;
10
use Drupal\graphql\Utility\StringHelper;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
13
/**
14
 * Create GraphQL entityById fields based on available Drupal entity types.
15
 */
16
class EntityByIdDeriver extends DeriverBase implements ContainerDeriverInterface {
17
18
  use StringTranslationTrait;
19
20
  /**
21
   * The entity type manager service.
22
   *
23
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
24
   */
25
  protected $entityTypeManager;
26
27
  /**
28
   * {@inheritdoc}
29
   */
30
  public static function create(ContainerInterface $container, $basePluginId) {
31
    return new static(
32
      $container->get('entity_type.manager')
33
    );
34
  }
35
36
  /**
37
   * {@inheritdoc}
38
   */
39
  public function __construct(
40
    EntityTypeManagerInterface $entityTypeManager
41
  ) {
42
    $this->entityTypeManager = $entityTypeManager;
43
  }
44
45
  /**
46
   * {@inheritdoc}
47
   */
48
  public function getDerivativeDefinitions($basePluginDefinition) {
49
    foreach ($this->entityTypeManager->getDefinitions() as $id => $type) {
50
      $derivative = [
51
        'name' => StringHelper::propCase($id, 'by', 'id'),
52
        'type' => StringHelper::camelCase($id),
53
        'description' => $this->t("Loads '@type' entities by their id.", ['@type' => $type->getLabel()]),
54
        'entity_type' => $id,
55
      ] + $basePluginDefinition;
56
57
      if ($type->isTranslatable()) {
58
        $derivative['arguments']['language'] = [
59
          'type' => 'AvailableLanguages',
60
          'nullable' => TRUE,
61
        ];
62
      }
63
64
      $this->derivatives["entity:$id"] = $derivative;
65
    }
66
67
    return parent::getDerivativeDefinitions($basePluginDefinition);
68
  }
69
70
}
71