Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / views / src / EntityViewsData.php
1 <?php
2
3 namespace Drupal\views;
4
5 use Drupal\Core\Entity\ContentEntityType;
6 use Drupal\Core\Entity\EntityHandlerInterface;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
10 use Drupal\Core\Entity\Sql\TableMappingInterface;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\Core\Field\FieldDefinitionInterface;
13 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 use Drupal\Core\StringTranslation\TranslationInterface;
15 use Symfony\Component\DependencyInjection\Container;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17
18 /**
19  * Provides generic views integration for entities.
20  */
21 class EntityViewsData implements EntityHandlerInterface, EntityViewsDataInterface {
22
23   use StringTranslationTrait;
24
25   /**
26    * Entity type for this views data handler instance.
27    *
28    * @var \Drupal\Core\Entity\EntityTypeInterface
29    */
30   protected $entityType;
31
32   /**
33    * The storage used for this entity type.
34    *
35    * @var \Drupal\Core\Entity\Sql\SqlEntityStorageInterface
36    */
37   protected $storage;
38
39   /**
40    * The module handler.
41    *
42    * @var \Drupal\Core\Extension\ModuleHandlerInterface
43    */
44   protected $moduleHandler;
45
46   /**
47    * The translation manager.
48    *
49    * @var \Drupal\Core\StringTranslation\TranslationInterface
50    */
51   protected $translationManager;
52
53   /**
54    * The field storage definitions for all base fields of the entity type.
55    *
56    * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
57    */
58   protected $fieldStorageDefinitions;
59
60   /**
61    * The entity manager.
62    *
63    * @var \Drupal\Core\Entity\EntityManagerInterface
64    */
65   protected $entityManager;
66
67   /**
68    * Constructs an EntityViewsData object.
69    *
70    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
71    *   The entity type to provide views integration for.
72    * @param \Drupal\Core\Entity\Sql\SqlEntityStorageInterface $storage_controller
73    *   The storage handler used for this entity type.
74    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
75    *   The entity manager.
76    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
77    *   The module handler.
78    * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
79    *   The translation manager.
80    */
81   public function __construct(EntityTypeInterface $entity_type, SqlEntityStorageInterface $storage_controller, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, TranslationInterface $translation_manager) {
82     $this->entityType = $entity_type;
83     $this->entityManager = $entity_manager;
84     $this->storage = $storage_controller;
85     $this->moduleHandler = $module_handler;
86     $this->setStringTranslation($translation_manager);
87   }
88
89   /**
90    * {@inheritdoc}
91    */
92   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
93     return new static(
94       $entity_type,
95       $container->get('entity.manager')->getStorage($entity_type->id()),
96       $container->get('entity.manager'),
97       $container->get('module_handler'),
98       $container->get('string_translation'),
99       $container->get('typed_data_manager')
100     );
101   }
102
103   /**
104    * Gets the field storage definitions.
105    *
106    * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
107    */
108   protected function getFieldStorageDefinitions() {
109     if (!isset($this->fieldStorageDefinitions)) {
110       $this->fieldStorageDefinitions = $this->entityManager->getFieldStorageDefinitions($this->entityType->id());
111     }
112     return $this->fieldStorageDefinitions;
113   }
114
115   /**
116    * {@inheritdoc}
117    */
118   public function getViewsData() {
119     $data = [];
120
121     $base_table = $this->entityType->getBaseTable() ?: $this->entityType->id();
122     $views_revision_base_table = NULL;
123     $revisionable = $this->entityType->isRevisionable();
124     $base_field = $this->entityType->getKey('id');
125
126     $revision_table = '';
127     if ($revisionable) {
128       $revision_table = $this->entityType->getRevisionTable() ?: $this->entityType->id() . '_revision';
129     }
130
131     $translatable = $this->entityType->isTranslatable();
132     $data_table = '';
133     if ($translatable) {
134       $data_table = $this->entityType->getDataTable() ?: $this->entityType->id() . '_field_data';
135     }
136
137     // Some entity types do not have a revision data table defined, but still
138     // have a revision table name set in
139     // \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout() so we
140     // apply the same kind of logic.
141     $revision_data_table = '';
142     if ($revisionable && $translatable) {
143       $revision_data_table = $this->entityType->getRevisionDataTable() ?: $this->entityType->id() . '_field_revision';
144     }
145     $revision_field = $this->entityType->getKey('revision');
146
147     // Setup base information of the views data.
148     $data[$base_table]['table']['group'] = $this->entityType->getLabel();
149     $data[$base_table]['table']['provider'] = $this->entityType->getProvider();
150
151     $views_base_table = $base_table;
152     if ($data_table) {
153       $views_base_table = $data_table;
154     }
155     $data[$views_base_table]['table']['base'] = [
156       'field' => $base_field,
157       'title' => $this->entityType->getLabel(),
158       'cache_contexts' => $this->entityType->getListCacheContexts(),
159     ];
160     $data[$base_table]['table']['entity revision'] = FALSE;
161
162     if ($label_key = $this->entityType->getKey('label')) {
163       if ($data_table) {
164         $data[$views_base_table]['table']['base']['defaults'] = [
165           'field' => $label_key,
166           'table' => $data_table,
167         ];
168       }
169       else {
170         $data[$views_base_table]['table']['base']['defaults'] = [
171           'field' => $label_key,
172         ];
173       }
174     }
175
176     // Entity types must implement a list_builder in order to use Views'
177     // entity operations field.
178     if ($this->entityType->hasListBuilderClass()) {
179       $data[$base_table]['operations'] = [
180         'field' => [
181           'title' => $this->t('Operations links'),
182           'help' => $this->t('Provides links to perform entity operations.'),
183           'id' => 'entity_operations',
184         ],
185       ];
186       $data[$revision_table]['operations'] = [
187         'field' => [
188           'title' => $this->t('Operations links'),
189           'help' => $this->t('Provides links to perform entity operations.'),
190           'id' => 'entity_operations',
191         ],
192       ];
193     }
194
195     if ($this->entityType->hasViewBuilderClass()) {
196       $data[$base_table]['rendered_entity'] = [
197         'field' => [
198           'title' => $this->t('Rendered entity'),
199           'help' => $this->t('Renders an entity in a view mode.'),
200           'id' => 'rendered_entity',
201         ],
202       ];
203     }
204
205     // Setup relations to the revisions/property data.
206     if ($data_table) {
207       $data[$base_table]['table']['join'][$data_table] = [
208         'left_field' => $base_field,
209         'field' => $base_field,
210         'type' => 'INNER',
211       ];
212       $data[$data_table]['table']['group'] = $this->entityType->getLabel();
213       $data[$data_table]['table']['provider'] = $this->entityType->getProvider();
214       $data[$data_table]['table']['entity revision'] = FALSE;
215     }
216     if ($revision_table) {
217       $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
218       $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
219
220       $views_revision_base_table = $revision_table;
221       if ($revision_data_table) {
222         $views_revision_base_table = $revision_data_table;
223       }
224       $data[$views_revision_base_table]['table']['entity revision'] = TRUE;
225       $data[$views_revision_base_table]['table']['base'] = [
226         'field' => $revision_field,
227         'title' => $this->t('@entity_type revisions', ['@entity_type' => $this->entityType->getLabel()]),
228       ];
229       // Join the revision table to the base table.
230       $data[$views_revision_base_table]['table']['join'][$views_base_table] = [
231         'left_field' => $revision_field,
232         'field' => $revision_field,
233         'type' => 'INNER',
234       ];
235
236       if ($revision_data_table) {
237         $data[$revision_data_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
238         $data[$revision_data_table]['table']['entity revision'] = TRUE;
239
240         $data[$revision_table]['table']['join'][$revision_data_table] = [
241           'left_field' => $revision_field,
242           'field' => $revision_field,
243           'type' => 'INNER',
244         ];
245       }
246
247       // Add a filter for showing only the latest revisions of an entity.
248       $data[$revision_table]['latest_revision'] = [
249         'title' => $this->t('Is Latest Revision'),
250         'help' => $this->t('Restrict the view to only revisions that are the latest revision of their entity.'),
251         'filter' => ['id' => 'latest_revision'],
252       ];
253     }
254
255     $this->addEntityLinks($data[$base_table]);
256     if ($views_revision_base_table) {
257       $this->addEntityLinks($data[$views_revision_base_table]);
258     }
259
260     // Load all typed data definitions of all fields. This should cover each of
261     // the entity base, revision, data tables.
262     $field_definitions = $this->entityManager->getBaseFieldDefinitions($this->entityType->id());
263     /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
264     if ($table_mapping = $this->storage->getTableMapping($field_definitions)) {
265       // Fetch all fields that can appear in both the base table and the data
266       // table.
267       $entity_keys = $this->entityType->getKeys();
268       $duplicate_fields = array_intersect_key($entity_keys, array_flip(['id', 'revision', 'bundle']));
269       // Iterate over each table we have so far and collect field data for each.
270       // Based on whether the field is in the field_definitions provided by the
271       // entity manager.
272       // @todo We should better just rely on information coming from the entity
273       //   storage.
274       // @todo https://www.drupal.org/node/2337511
275       foreach ($table_mapping->getTableNames() as $table) {
276         foreach ($table_mapping->getFieldNames($table) as $field_name) {
277           // To avoid confusing duplication in the user interface, for fields
278           // that are on both base and data tables, only add them on the data
279           // table (same for revision vs. revision data).
280           if ($data_table && ($table === $base_table || $table === $revision_table) && in_array($field_name, $duplicate_fields)) {
281             continue;
282           }
283           $this->mapFieldDefinition($table, $field_name, $field_definitions[$field_name], $table_mapping, $data[$table]);
284         }
285       }
286
287       foreach ($field_definitions as $field_definition) {
288         if ($table_mapping->requiresDedicatedTableStorage($field_definition->getFieldStorageDefinition())) {
289           $table = $table_mapping->getDedicatedDataTableName($field_definition->getFieldStorageDefinition());
290
291           $data[$table]['table']['group'] = $this->entityType->getLabel();
292           $data[$table]['table']['provider'] = $this->entityType->getProvider();
293           $data[$table]['table']['join'][$views_base_table] = [
294             'left_field' => $base_field,
295             'field' => 'entity_id',
296             'extra' => [
297               ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
298             ],
299           ];
300
301           if ($revisionable) {
302             $revision_table = $table_mapping->getDedicatedRevisionTableName($field_definition->getFieldStorageDefinition());
303
304             $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
305             $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
306             $data[$revision_table]['table']['join'][$views_revision_base_table] = [
307               'left_field' => $revision_field,
308               'field' => 'entity_id',
309               'extra' => [
310                 ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
311               ],
312             ];
313           }
314         }
315       }
316     }
317
318     // Add the entity type key to each table generated.
319     $entity_type_id = $this->entityType->id();
320     array_walk($data, function (&$table_data) use ($entity_type_id) {
321       $table_data['table']['entity type'] = $entity_type_id;
322     });
323
324     return $data;
325   }
326
327   /**
328    * Sets the entity links in case corresponding link templates exist.
329    *
330    * @param array $data
331    *   The views data of the base table.
332    */
333   protected function addEntityLinks(array &$data) {
334     $entity_type_id = $this->entityType->id();
335     $t_arguments = ['@entity_type_label' => $this->entityType->getLabel()];
336     if ($this->entityType->hasLinkTemplate('canonical')) {
337       $data['view_' . $entity_type_id] = [
338         'field' => [
339           'title' => $this->t('Link to @entity_type_label', $t_arguments),
340           'help' => $this->t('Provide a view link to the @entity_type_label.', $t_arguments),
341           'id' => 'entity_link',
342         ],
343       ];
344     }
345     if ($this->entityType->hasLinkTemplate('edit-form')) {
346       $data['edit_' . $entity_type_id] = [
347         'field' => [
348           'title' => $this->t('Link to edit @entity_type_label', $t_arguments),
349           'help' => $this->t('Provide an edit link to the @entity_type_label.', $t_arguments),
350           'id' => 'entity_link_edit',
351         ],
352       ];
353     }
354     if ($this->entityType->hasLinkTemplate('delete-form')) {
355       $data['delete_' . $entity_type_id] = [
356         'field' => [
357           'title' => $this->t('Link to delete @entity_type_label', $t_arguments),
358           'help' => $this->t('Provide a delete link to the @entity_type_label.', $t_arguments),
359           'id' => 'entity_link_delete',
360         ],
361       ];
362     }
363   }
364
365   /**
366    * Puts the views data for a single field onto the views data.
367    *
368    * @param string $table
369    *   The table of the field to handle.
370    * @param string $field_name
371    *   The name of the field to handle.
372    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
373    *   The field definition defined in Entity::baseFieldDefinitions()
374    * @param \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping
375    *   The table mapping information
376    * @param array $table_data
377    *   A reference to a specific entity table (for example data_table) inside
378    *   the views data.
379    */
380   protected function mapFieldDefinition($table, $field_name, FieldDefinitionInterface $field_definition, TableMappingInterface $table_mapping, &$table_data) {
381     // Create a dummy instance to retrieve property definitions.
382     $field_column_mapping = $table_mapping->getColumnNames($field_name);
383     $field_schema = $this->getFieldStorageDefinitions()[$field_name]->getSchema();
384
385     $field_definition_type = $field_definition->getType();
386     // Add all properties to views table data. We need an entry for each
387     // column of each field, with the first one given special treatment.
388     // @todo Introduce concept of the "main" column for a field, rather than
389     //   assuming the first one is the main column. See also what the
390     //   mapSingleFieldViewsData() method does with $first.
391     $first = TRUE;
392     foreach ($field_column_mapping as $field_column_name => $schema_field_name) {
393       $table_data[$schema_field_name] = $this->mapSingleFieldViewsData($table, $field_name, $field_definition_type, $field_column_name, $field_schema['columns'][$field_column_name]['type'], $first, $field_definition);
394       $table_data[$schema_field_name]['entity field'] = $field_name;
395       $first = FALSE;
396     }
397   }
398
399   /**
400    * Provides the views data for a given data type and schema field.
401    *
402    * @param string $table
403    *   The table of the field to handle.
404    * @param string $field_name
405    *   The machine name of the field being processed.
406    * @param string $field_type
407    *   The type of field being handled.
408    * @param string $column_name
409    *   For fields containing multiple columns, the column name being processed.
410    * @param string $column_type
411    *   Within the field, the column type being handled.
412    * @param bool $first
413    *   TRUE if this is the first column within the field.
414    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
415    *   The field definition.
416    *
417    * @return array
418    *   The modified views data field definition.
419    */
420   protected function mapSingleFieldViewsData($table, $field_name, $field_type, $column_name, $column_type, $first, FieldDefinitionInterface $field_definition) {
421     $views_field = [];
422
423     // Provide a nicer, less verbose label for the first column within a field.
424     // @todo Introduce concept of the "main" column for a field, rather than
425     //   assuming the first one is the main column.
426     if ($first) {
427       $views_field['title'] = $field_definition->getLabel();
428     }
429     else {
430       $views_field['title'] = $field_definition->getLabel() . " ($column_name)";
431     }
432
433     if ($description = $field_definition->getDescription()) {
434       $views_field['help'] = $description;
435     }
436
437     // Set up the field, sort, argument, and filters, based on
438     // the column and/or field data type.
439     // @todo Allow field types to customize this.
440     // @see https://www.drupal.org/node/2337515
441     switch ($field_type) {
442       // Special case a few field types.
443       case 'timestamp':
444       case 'created':
445       case 'changed':
446         $views_field['field']['id'] = 'field';
447         $views_field['argument']['id'] = 'date';
448         $views_field['filter']['id'] = 'date';
449         $views_field['sort']['id'] = 'date';
450         break;
451
452       case 'language':
453         $views_field['field']['id'] = 'field';
454         $views_field['argument']['id'] = 'language';
455         $views_field['filter']['id'] = 'language';
456         $views_field['sort']['id'] = 'standard';
457         break;
458
459       case 'boolean':
460         $views_field['field']['id'] = 'field';
461         $views_field['argument']['id'] = 'numeric';
462         $views_field['filter']['id'] = 'boolean';
463         $views_field['sort']['id'] = 'standard';
464         break;
465
466       case 'uri':
467         // Let's render URIs as URIs by default, not links.
468         $views_field['field']['id'] = 'field';
469         $views_field['field']['default_formatter'] = 'string';
470
471         $views_field['argument']['id'] = 'string';
472         $views_field['filter']['id'] = 'string';
473         $views_field['sort']['id'] = 'standard';
474         break;
475
476       case 'text':
477       case 'text_with_summary':
478         // Treat these three long text fields the same.
479         $field_type = 'text_long';
480         // Intentional fall-through here to the default processing!
481
482       default:
483         // For most fields, the field type is generic enough to just use
484         // the column type to determine the filters etc.
485         switch ($column_type) {
486
487           case 'int':
488           case 'integer':
489           case 'smallint':
490           case 'tinyint':
491           case 'mediumint':
492           case 'float':
493           case 'double':
494           case 'decimal':
495             $views_field['field']['id'] = 'field';
496             $views_field['argument']['id'] = 'numeric';
497             $views_field['filter']['id'] = 'numeric';
498             $views_field['sort']['id'] = 'standard';
499             break;
500
501           case 'char':
502           case 'string':
503           case 'varchar':
504           case 'varchar_ascii':
505           case 'tinytext':
506           case 'text':
507           case 'mediumtext':
508           case 'longtext':
509             $views_field['field']['id'] = 'field';
510             $views_field['argument']['id'] = 'string';
511             $views_field['filter']['id'] = 'string';
512             $views_field['sort']['id'] = 'standard';
513             break;
514
515           default:
516             $views_field['field']['id'] = 'field';
517             $views_field['argument']['id'] = 'standard';
518             $views_field['filter']['id'] = 'standard';
519             $views_field['sort']['id'] = 'standard';
520         }
521     }
522
523     // Do post-processing for a few field types.
524
525     $process_method = 'processViewsDataFor' . Container::camelize($field_type);
526     if (method_exists($this, $process_method)) {
527       $this->{$process_method}($table, $field_definition, $views_field, $column_name);
528     }
529
530     return $views_field;
531   }
532
533   /**
534    * Processes the views data for a language field.
535    *
536    * @param string $table
537    *   The table the language field is added to.
538    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
539    *   The field definition.
540    * @param array $views_field
541    *   The views field data.
542    * @param string $field_column_name
543    *   The field column being processed.
544    */
545   protected function processViewsDataForLanguage($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
546     // Apply special titles for the langcode field.
547     if ($field_definition->getName() == $this->entityType->getKey('langcode')) {
548       if ($table == $this->entityType->getDataTable() || $table == $this->entityType->getRevisionDataTable()) {
549         $views_field['title'] = $this->t('Translation language');
550       }
551       if ($table == $this->entityType->getBaseTable() || $table == $this->entityType->getRevisionTable()) {
552         $views_field['title'] = $this->t('Original language');
553       }
554     }
555   }
556
557   /**
558    * Processes the views data for an entity reference field.
559    *
560    * @param string $table
561    *   The table the language field is added to.
562    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
563    *   The field definition.
564    * @param array $views_field
565    *   The views field data.
566    * @param string $field_column_name
567    *   The field column being processed.
568    */
569   protected function processViewsDataForEntityReference($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
570
571     // @todo Should the actual field handler respect that this just renders a
572     //   number?
573     // @todo Create an optional entity field handler, that can render the
574     //   entity.
575     // @see https://www.drupal.org/node/2322949
576
577     if ($entity_type_id = $field_definition->getItemDefinition()->getSetting('target_type')) {
578       $entity_type = $this->entityManager->getDefinition($entity_type_id);
579       if ($entity_type instanceof ContentEntityType) {
580         $views_field['relationship'] = [
581           'base' => $this->getViewsTableForEntityType($entity_type),
582           'base field' => $entity_type->getKey('id'),
583           'label' => $entity_type->getLabel(),
584           'title' => $entity_type->getLabel(),
585           'id' => 'standard',
586         ];
587         $views_field['field']['id'] = 'field';
588         $views_field['argument']['id'] = 'numeric';
589         $views_field['filter']['id'] = 'numeric';
590         $views_field['sort']['id'] = 'standard';
591       }
592       else {
593         $views_field['field']['id'] = 'field';
594         $views_field['argument']['id'] = 'string';
595         $views_field['filter']['id'] = 'string';
596         $views_field['sort']['id'] = 'standard';
597       }
598     }
599
600     if ($field_definition->getName() == $this->entityType->getKey('bundle')) {
601       $views_field['filter']['id'] = 'bundle';
602     }
603   }
604
605   /**
606    * Processes the views data for a text field with formatting.
607    *
608    * @param string $table
609    *   The table the field is added to.
610    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
611    *   The field definition.
612    * @param array $views_field
613    *   The views field data.
614    * @param string $field_column_name
615    *   The field column being processed.
616    */
617   protected function processViewsDataForTextLong($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
618     // Connect the text field to its formatter.
619     if ($field_column_name == 'value') {
620       $views_field['field']['format'] = $field_definition->getName() . '__format';
621       $views_field['field']['id'] = 'field';
622     }
623   }
624
625   /**
626    * Processes the views data for a UUID field.
627    *
628    * @param string $table
629    *   The table the field is added to.
630    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
631    *   The field definition.
632    * @param array $views_field
633    *   The views field data.
634    * @param string $field_column_name
635    *   The field column being processed.
636    */
637   protected function processViewsDataForUuid($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
638     // It does not make sense for UUID fields to be click sortable.
639     $views_field['field']['click sortable'] = FALSE;
640   }
641
642   /**
643    * {@inheritdoc}
644    */
645   public function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
646     return $entity_type->getDataTable() ?: $entity_type->getBaseTable();
647   }
648
649 }