Completed
Push — 8.x-3.x ( fe11c4...e66de4 )
by Sebastian
08:05 queued 05:10
created

EntityReferenceReverseDeriver::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 7
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\EntityFieldManagerInterface;
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\Core\Entity\FieldableEntityInterface;
9
use Drupal\Core\Field\BaseFieldDefinition;
10
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
11
use Drupal\Core\StringTranslation\StringTranslationTrait;
12
use Drupal\Core\TypedData\TypedDataManagerInterface;
13
use Drupal\graphql\Utility\StringHelper;
14
use Drupal\graphql_core\Plugin\GraphQL\Interfaces\Entity\Entity;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
17
class EntityReferenceReverseDeriver extends DeriverBase implements ContainerDeriverInterface {
18
  use StringTranslationTrait;
19
20
  /**
21
   * The entity type manager.
22
   *
23
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
24
   */
25
  protected $entityTypeManager;
26
27
  /**
28
   * The entity field manager.
29
   *
30
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
31
   */
32
  protected $entityFieldManager;
33
34
  /**
35
   * The typed data manager service.
36
   *
37
   * @var \Drupal\Core\TypedData\TypedDataManagerInterface
38
   */
39
  protected $typedDataManager;
40
41
  /**
42
   * {@inheritdoc}
43
   */
44
  public static function create(ContainerInterface $container, $basePluginId) {
45
    return new static(
46
      $container->get('entity_type.manager'),
47
      $container->get('entity_field.manager'),
48
      $container->get('typed_data_manager')
49
    );
50
  }
51
52
  /**
53
   * RawValueFieldItemDeriver constructor.
54
   *
55
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
56
   *   The entity type manager.
57
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
58
   *   The entity field manager.
59
   * @param \Drupal\Core\TypedData\TypedDataManagerInterface $typedDataManager
60
   *   The typed data manager service.
61
   */
62
  public function __construct(
63
    EntityTypeManagerInterface $entityTypeManager,
64
    EntityFieldManagerInterface $entityFieldManager,
65
    TypedDataManagerInterface $typedDataManager
66
  ) {
67
    $this->entityTypeManager = $entityTypeManager;
68
    $this->entityFieldManager = $entityFieldManager;
69
    $this->typedDataManager = $typedDataManager;
70
  }
71
72
  /**
73
   * {@inheritdoc}
74
   */
75
  public function getDerivativeDefinitions($basePluginDefinition) {
76
    foreach ($this->entityTypeManager->getDefinitions() as $entityTypeId => $entityType) {
77
      $interfaces = class_implements($entityType->getClass());
78
      if (!array_key_exists(FieldableEntityInterface::class, $interfaces)) {
79
        continue;
80
      }
81
82
      foreach ($this->entityFieldManager->getFieldStorageDefinitions($entityTypeId) as $fieldDefinition) {
83
        if ($fieldDefinition->getType() !== 'entity_reference' || !$targetTypeId = $fieldDefinition->getSetting('target_type')) {
84
          continue;
85
        }
86
87
        $fieldName = $fieldDefinition->getName();
88
        $derivative = [
89
          'parents' => [Entity::getId($targetTypeId)],
90
          'name' => StringHelper::propCase('reverse', $fieldName, $entityTypeId),
91
          'description' => $this->t('Reverse reference: @description', [
92
            '@description' => $fieldDefinition->getDescription(),
93
          ]),
94
          'field' => $fieldName,
95
          'entity_type' => $entityTypeId,
96
          'schema_cache_tags' => array_merge($fieldDefinition->getCacheTags(), ['entity_field_info']),
97
          'schema_cache_contexts' => $fieldDefinition->getCacheContexts(),
98
          'schema_cache_max_age' => $fieldDefinition->getCacheMaxAge(),
99
        ];
100
101
        /** @var \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface $definition */
102
        $definition = $this->typedDataManager->createDataDefinition("entity:$targetTypeId");
103
        $properties = $definition->getPropertyDefinitions();
104
        $queryableProperties = array_filter($properties, function ($property) {
105
          return $property instanceof BaseFieldDefinition && $property->isQueryable();
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Field\BaseFieldDefinition 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
        });
107
108 View Code Duplication
        if (!empty($queryableProperties)) {
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...
109
          $derivative['arguments']['filter'] = [
110
            'multi' => FALSE,
111
            'nullable' => TRUE,
112
            'type' => StringHelper::camelCase($targetTypeId, 'query', 'filter', 'input'),
113
          ];
114
        }
115
116
        $this->derivatives["$entityTypeId-$fieldName"] = $derivative + $basePluginDefinition;
117
      }
118
    }
119
120
    return $this->derivatives;
121
  }
122
}
123