You are here

public function ViewsData::alterViewsData in Plugin 8.2

Implements hook_views_data_alter().

File

src/ViewsData.php, line 59

Class

ViewsData
Provides/alters Views data.

Namespace

Drupal\plugin

Code

public function alterViewsData(array &$data) {

  // We need to work with entity type database table mappings, which are
  // available per entity type.
  foreach ($this->entityTypeManager
    ->getDefinitions() as $entity_type) {

    // Skip non-fieldable entity types.
    if (!$entity_type
      ->entityClassImplements(FieldableEntityInterface::class)) {
      continue;
    }
    $base_field_definitions = $this->entityFieldManager
      ->getBaseFieldDefinitions($entity_type
      ->id());
    $entity_storage = $this->entityTypeManager
      ->getStorage($entity_type
      ->id());

    // We cannot alter Views data if we cannot map fields to tables.
    if (!$entity_storage instanceof SqlEntityStorageInterface) {
      continue;
    }
    $table_mapping = $entity_storage
      ->getTableMapping();

    // Loop through all of this entity type's stored fields.
    foreach ($table_mapping
      ->getTableNames() as $table_name) {
      foreach ($table_mapping
        ->getFieldNames($table_name) as $field_name) {

        // Skip fields that are no base fields.
        if (!isset($base_field_definitions[$field_name])) {
          continue;
        }
        $base_field_storage_definition = $base_field_definitions[$field_name]
          ->getFieldStorageDefinition();

        // Skip if this is no "plugin" base field.
        if (strpos($base_field_storage_definition
          ->getType(), 'plugin:') !== 0) {
          continue;
        }

        // Get the column names.
        if ($base_field_storage_definition
          ->getCardinality() == 1) {
          $plugin_id_column_name = $table_mapping
            ->getFieldColumnName($base_field_storage_definition, 'plugin_id');
          $plugin_configuration_column_name = $table_mapping
            ->getFieldColumnName($base_field_storage_definition, 'plugin_configuration');
        }
        else {
          $plugin_id_column_name = $base_field_storage_definition
            ->getName() . '__plugin_id';
          $plugin_configuration_column_name = $base_field_storage_definition
            ->getName() . '__plugin_configuration';
        }
        $this
          ->alterPluginFieldData($data, $base_field_storage_definition, $table_name, $plugin_id_column_name, $plugin_configuration_column_name);
      }
    }
  }
}