EntityViewsData.php 18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
<?php

/**
 * @file
 * Contains \Drupal\views\EntityViewsData.
 */

namespace Drupal\views;

use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
use Drupal\Core\Entity\Sql\TableMappingInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides generic views integration for entities.
 */
class EntityViewsData implements EntityHandlerInterface, EntityViewsDataInterface {

  use StringTranslationTrait;

  /**
   * Entity type for this views controller instance.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityType;

  /**
   * The storage used for this entity type.
   *
   * @var \Drupal\Core\Entity\Sql\SqlEntityStorageInterface
   */
  protected $storage;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The translation manager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

  /**
   * The field storage definitions for all base fields of the entity type.
   *
   * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
   */
  protected $fieldStorageDefinitions;

  /**
   * Constructs an EntityViewsData object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type to provide views integration for.
   * @param \Drupal\Core\Entity\Sql\SqlEntityStorageInterface $storage_controller
   *   The storage controller used for this entity type.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The translation manager.
   */
  function __construct(EntityTypeInterface $entity_type, SqlEntityStorageInterface $storage_controller, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, TranslationInterface $translation_manager) {
    $this->entityType = $entity_type;
    $this->entityManager = $entity_manager;
    $this->storage = $storage_controller;
    $this->moduleHandler = $module_handler;
    $this->setStringTranslation($translation_manager);
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('entity.manager')->getStorage($entity_type->id()),
      $container->get('entity.manager'),
      $container->get('module_handler'),
      $container->get('string_translation'),
      $container->get('typed_data_manager')
    );
  }

  /**
   * Gets the field storage definitions.
   *
   * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
   */
  protected function getFieldStorageDefinitions() {
    if (!isset($this->fieldStorageDefinitions)) {
      $this->fieldStorageDefinitions = $this->entityManager->getFieldStorageDefinitions($this->entityType->id());
    }
    return $this->fieldStorageDefinitions;
  }

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = [];

    // @todo In theory we should use the data table as base table, as this would
    //   save one pointless join (and one more for every relationship).
    // @see https://drupal.org/node/2337509
    $base_table = $this->entityType->getBaseTable();
    $base_field = $this->entityType->getKey('id');
    $data_table = $this->entityType->getDataTable();
    $revision_table = $this->entityType->getRevisionTable();
    $revision_data_table = $this->entityType->getRevisionDataTable();
    $revision_field = $this->entityType->getKey('revision');

    // Setup base information of the views data.
    $data[$base_table]['table']['group'] = $this->entityType->getLabel();
131
    $data[$base_table]['table']['provider'] = $this->entityType->getProvider();
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    $data[$base_table]['table']['base'] = [
      'field' => $base_field,
      'title' => $this->entityType->getLabel(),
    ];

    if ($label_key = $this->entityType->getKey('label')) {
      if ($data_table) {
        $data[$base_table]['table']['base']['defaults'] = array(
          'field' => $label_key,
          'table' => $data_table,
        );
      }
      else {
        $data[$base_table]['table']['base']['defaults'] = array(
          'field' => $label_key,
        );
      }
    }

    // Setup relations to the revisions/property data.
    if ($data_table) {
      $data[$data_table]['table']['join'][$base_table] = [
        'left_field' => $base_field,
        'field' => $base_field,
        'type' => 'INNER'
      ];
      $data[$data_table]['table']['group'] = $this->entityType->getLabel();
159
      $data[$data_table]['table']['provider'] = $this->entityType->getProvider();
160 161 162
    }
    if ($revision_table) {
      $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
163
      $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      $data[$revision_table]['table']['base'] = array(
        'field' => $revision_field,
        'title' => $this->t('@entity_type revisions', array('@entity_type' => $this->entityType->getLabel())),
      );
      // Join the revision table to the base table.
      $data[$revision_table]['table']['join'][$base_table] = array(
        'left_field' => $revision_field,
        'field' => $revision_field,
        'type' => 'INNER',
      );

      if ($revision_data_table) {
        $data[$revision_data_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);

        $data[$revision_data_table]['table']['join'][$revision_table] = array(
          'left_field' => $revision_field,
          'field' => $revision_field,
          'type' => 'INNER',
        );
      }
    }

    // Load all typed data definitions of all fields. This should cover each of
    // the entity base, revision, data tables.
    $field_definitions = $this->entityManager->getBaseFieldDefinitions($this->entityType->id());
    if ($table_mapping = $this->storage->getTableMapping()) {
      // Iterate over each table we have so far and collect field data for each.
      // Based on whether the field is in the field_definitions provided by the
      // entity manager.
      // @todo We should better just rely on information coming from the entity
      //   storage.
      // @todo https://drupal.org/node/2337511
      foreach ($table_mapping->getTableNames() as $table) {
        foreach ($table_mapping->getFieldNames($table) as $field_name) {
          $this->mapFieldDefinition($table, $field_name, $field_definitions[$field_name], $table_mapping, $data[$table]);
        }
      }
    }

203 204 205 206 207 208
    // Add the entity type key to each table generated.
    $entity_type_id = $this->entityType->id();
    array_walk($data, function(&$table_data) use ($entity_type_id){
      $table_data['table']['entity type'] = $entity_type_id;
    });

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    return $data;
  }

  /**
   * Puts the views data for a single field onto the views data.
   *
   * @param string $table
   *   The table of the field to handle.
   * @param string $field_name
   *   The name of the field to handle.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition defined in Entity::baseFieldDefinitions()
   * @param \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping
   *   The table mapping information
   * @param array $table_data
   *   A reference to a specific entity table (for example data_table) inside
   *   the views data.
   */
  protected function mapFieldDefinition($table, $field_name, FieldDefinitionInterface $field_definition, TableMappingInterface $table_mapping, &$table_data) {
    // Create a dummy instance to retrieve property definitions.
    $field_column_mapping = $table_mapping->getColumnNames($field_name);
    $field_schema = $this->getFieldStorageDefinitions()[$field_name]->getSchema();

    $field_definition_type = $field_definition->getType();
233 234 235 236 237 238
    // Add all properties to views table data. We need an entry for each
    // column of each field, with the first one given special treatment.
    // @todo Introduce concept of the "main" column for a field, rather than
    //   assuming the first one is the main column. See also what the
    //   mapSingleFieldViewsData() method does with $first.
    $multiple = (count($field_column_mapping) > 1);
239 240
    $first = TRUE;
    foreach ($field_column_mapping as $field_column_name => $schema_field_name) {
241 242
      $views_field_name = ($multiple) ? $field_name . '__' . $field_column_name : $field_name;
      $table_data[$views_field_name] = $this->mapSingleFieldViewsData($table, $field_name, $field_definition_type, $field_column_name, $field_schema['columns'][$field_column_name]['type'], $first, $field_definition);
243 244

      $table_data[$views_field_name]['entity field'] = $field_name;
245
      $first = FALSE;
246 247 248 249 250 251 252 253
    }
  }

  /**
   * Provides the views data for a given data type and schema field.
   *
   * @param string $table
   *   The table of the field to handle.
254 255 256 257 258 259 260 261 262 263
   * @param string $field_name
   *   The machine name of the field being processed.
   * @param string $field_type
   *   The type of field being handled.
   * @param string $column_name
   *   For fields containing multiple columns, the column name being processed.
   * @param string $column_type
   *   Within the field, the column type being handled.
   * @param bool $first
   *   TRUE if this is the first column within the field.
264 265 266 267 268 269
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   *
   * @return array
   *   The modified views data field definition.
   */
270
  protected function mapSingleFieldViewsData($table, $field_name, $field_type, $column_name, $column_type, $first, FieldDefinitionInterface $field_definition) {
271 272
    $views_field = array();

273 274 275
    // Provide a nicer, less verbose label for the first column within a field.
    // @todo Introduce concept of the "main" column for a field, rather than
    //   assuming the first one is the main column.
276 277 278 279
    if ($first) {
      $views_field['title'] = $field_definition->getLabel();
    }
    else {
280
      $views_field['title'] = $field_definition->getLabel() . " ($column_name)";
281 282 283 284 285 286
    }

    if ($description = $field_definition->getDescription()) {
      $views_field['help'] = $description;
    }

287 288
    // Set up the field, sort, argument, and filters, based on
    // the column and/or field data type.
289 290
    // @todo Allow field types to customize this.
    // @see https://www.drupal.org/node/2337515
291 292 293 294 295 296 297 298 299
    switch ($field_type) {
      // Special case a few field types.
      case 'timestamp':
      case 'created':
      case 'changed':
        $views_field['field']['id'] = 'date';
        $views_field['argument']['id'] = 'date';
        $views_field['filter']['id'] = 'date';
        $views_field['sort']['id'] = 'date';
300
        break;
301

302 303 304 305 306 307
      case 'language':
        $views_field['field']['id'] = 'language';
        $views_field['argument']['id'] = 'language';
        $views_field['filter']['id'] = 'language';
        $views_field['sort']['id'] = 'standard';
        break;
308 309 310 311 312

      case 'boolean':
        $views_field['field']['id'] = 'boolean';
        $views_field['argument']['id'] = 'numeric';
        $views_field['filter']['id'] = 'boolean';
313 314
        $views_field['sort']['id'] = 'standard';
        break;
315

316 317 318 319 320 321 322
      case 'uri':
        $views_field['field']['id'] = 'url';
        $views_field['argument']['id'] = 'string';
        $views_field['filter']['id'] = 'string';
        $views_field['sort']['id'] = 'standard';
        break;

323 324 325 326 327 328
      case 'text':
      case 'text_with_summary':
        // Treat these three long text fields the same.
        $field_type = 'text_long';
        // Intentional fall-through here to the default processing!

329
      default:
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        // For most fields, the field type is generic enough to just use
        // the column type to determine the filters etc.
        switch ($column_type) {

          case 'int':
          case 'integer':
          case 'smallint':
          case 'tinyint':
          case 'mediumint':
          case 'float':
          case 'double':
          case 'decimal':
            $views_field['field']['id'] = 'numeric';
            $views_field['argument']['id'] = 'numeric';
            $views_field['filter']['id'] = 'numeric';
            $views_field['sort']['id'] = 'standard';
            break;

          case 'char':
          case 'string':
          case 'varchar':
          case 'tinytext':
          case 'text':
          case 'mediumtext':
          case 'longtext':
            $views_field['field']['id'] = 'standard';
            $views_field['argument']['id'] = 'string';
            $views_field['filter']['id'] = 'string';
            $views_field['sort']['id'] = 'standard';
            break;

          default:
            $views_field['field']['id'] = 'standard';
            $views_field['argument']['id'] = 'standard';
            $views_field['filter']['id'] = 'standard';
            $views_field['sort']['id'] = 'standard';
        }
367 368
    }

369 370 371
    // Do post-processing for a few field types.

    $process_method = 'processViewsDataFor' . Container::camelize($field_type);
372
    if (method_exists($this, $process_method)) {
373
      $this->{$process_method}($table, $field_definition, $views_field, $column_name);
374 375 376 377 378 379 380 381 382 383 384 385 386 387
    }

    return $views_field;
  }

  /**
   * Processes the views data for a language field.
   *
   * @param string $table
   *   The table the language field is added to.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param array $views_field
   *   The views field data.
388 389
   * @param string $field_column_name
   *   The field column being processed.
390
   */
391
  protected function processViewsDataForLanguage($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
392
    // Apply special titles for the langcode field.
393
    if ($field_definition->getName() == $this->entityType->getKey('langcode')) {
394
      if ($table == $this->entityType->getDataTable() || $table == $this->entityType->getRevisionDataTable()) {
395 396
        $views_field['title'] = $this->t('Translation language');
      }
397
      if ($table == $this->entityType->getBaseTable() || $table == $this->entityType->getRevisionTable()) {
398 399 400 401 402 403 404 405 406 407 408 409 410 411
        $views_field['title'] =  $this->t('Original language');
      }
    }
  }

  /**
   * Processes the views data for an entity reference field.
   *
   * @param string $table
   *   The table the language field is added to.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param array $views_field
   *   The views field data.
412 413
   * @param string $field_column_name
   *   The field column being processed.
414
   */
415 416 417 418 419 420 421 422
  protected function processViewsDataForEntityReference($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {

    // @todo Should the actual field handler respect that this just renders a
    //   number?
    // @todo Create an optional entity field handler, that can render the
    //   entity.
    // @see https://www.drupal.org/node/2322949

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    if ($entity_type_id = $field_definition->getItemDefinition()->getSetting('target_type')) {
      $entity_type = $this->entityManager->getDefinition($entity_type_id);
      if ($entity_type instanceof ContentEntityType) {
        $views_field['relationship'] = [
          'base' => $this->getViewsTableForEntityType($entity_type),
          'base field' => $entity_type->getKey('id'),
          'label' => $entity_type->getLabel(),
          'title' => $entity_type->getLabel(),
          'id' => 'standard',
        ];
        $views_field['field']['id'] = 'numeric';
        $views_field['argument']['id'] = 'numeric';
        $views_field['filter']['id'] = 'numeric';
        $views_field['sort']['id'] = 'standard';
      }
      else {
        $views_field['field']['id'] = 'standard';
        $views_field['argument']['id'] = 'string';
        $views_field['filter']['id'] = 'string';
        $views_field['sort']['id'] = 'standard';
      }
    }

    if ($field_definition->getName() == $this->entityType->getKey('bundle')) {
      // @todo Use the other bundle handlers, once
      //   https://www.drupal.org/node/2322949 is in.
      $views_field['filter']['id'] = 'bundle';
    }
  }

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  /**
   * Processes the views data for a text field with formatting.
   *
   * @param string $table
   *   The table the field is added to.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param array $views_field
   *   The views field data.
   * @param string $field_column_name
   *   The field column being processed.
   */
  protected function processViewsDataForTextLong($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
    // Connect the text field to its formatter.
    if ($field_column_name == 'value') {
      $views_field['field']['format'] = $field_definition->getName() . '__format';
      $views_field['field']['id'] = 'markup';
    }
  }

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  /**
   * Gets the table of an entity type to be used as base table in views.
   *
   * @todo Given that the base_table is pretty much useless as you often have to
   *   join to the data table anyway, it could make a lot of sense to start with
   *   the data table right from the beginning.
   * @see https://drupal.org/node/2337509
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type.
   *
   * @return string
   *   The name of the base table in views.
   */
  protected function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
    return $entity_type->getBaseTable();
  }

}