annotate core/lib/Drupal/Core/Entity/EntityViewBuilder.php @ 12:7a779792577d

Update Drupal core to v8.4.5 (via Composer)
author Chris Cannam
date Fri, 23 Feb 2018 15:52:07 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Entity;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\Crypt;
Chris@0 6 use Drupal\Core\Cache\Cache;
Chris@0 7 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
Chris@0 8 use Drupal\Core\Entity\Entity\EntityViewDisplay;
Chris@0 9 use Drupal\Core\Field\FieldItemInterface;
Chris@0 10 use Drupal\Core\Field\FieldItemListInterface;
Chris@0 11 use Drupal\Core\Language\LanguageManagerInterface;
Chris@0 12 use Drupal\Core\Render\Element;
Chris@0 13 use Drupal\Core\Theme\Registry;
Chris@0 14 use Drupal\Core\TypedData\TranslatableInterface;
Chris@0 15 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Base class for entity view builders.
Chris@0 19 *
Chris@0 20 * @ingroup entity_api
Chris@0 21 */
Chris@0 22 class EntityViewBuilder extends EntityHandlerBase implements EntityHandlerInterface, EntityViewBuilderInterface {
Chris@0 23
Chris@0 24 /**
Chris@0 25 * The type of entities for which this view builder is instantiated.
Chris@0 26 *
Chris@0 27 * @var string
Chris@0 28 */
Chris@0 29 protected $entityTypeId;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * Information about the entity type.
Chris@0 33 *
Chris@0 34 * @var \Drupal\Core\Entity\EntityTypeInterface
Chris@0 35 */
Chris@0 36 protected $entityType;
Chris@0 37
Chris@0 38 /**
Chris@0 39 * The entity manager service.
Chris@0 40 *
Chris@0 41 * @var \Drupal\Core\Entity\EntityManagerInterface
Chris@0 42 */
Chris@0 43 protected $entityManager;
Chris@0 44
Chris@0 45 /**
Chris@0 46 * The cache bin used to store the render cache.
Chris@0 47 *
Chris@0 48 * @var string
Chris@0 49 */
Chris@0 50 protected $cacheBin = 'render';
Chris@0 51
Chris@0 52 /**
Chris@0 53 * The language manager.
Chris@0 54 *
Chris@12 55 * @var \Drupal\Core\Language\LanguageManagerInterface
Chris@0 56 */
Chris@0 57 protected $languageManager;
Chris@0 58
Chris@0 59 /**
Chris@0 60 * The theme registry.
Chris@0 61 *
Chris@0 62 * @var \Drupal\Core\Theme\Registry
Chris@0 63 */
Chris@0 64 protected $themeRegistry;
Chris@0 65
Chris@0 66 /**
Chris@0 67 * The EntityViewDisplay objects created for individual field rendering.
Chris@0 68 *
Chris@12 69 * @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface[]
Chris@12 70 *
Chris@0 71 * @see \Drupal\Core\Entity\EntityViewBuilder::getSingleFieldDisplay()
Chris@0 72 */
Chris@0 73 protected $singleFieldDisplays;
Chris@0 74
Chris@0 75 /**
Chris@0 76 * Constructs a new EntityViewBuilder.
Chris@0 77 *
Chris@0 78 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
Chris@0 79 * The entity type definition.
Chris@0 80 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
Chris@0 81 * The entity manager service.
Chris@0 82 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
Chris@0 83 * The language manager.
Chris@0 84 * @param \Drupal\Core\Theme\Registry $theme_registry
Chris@0 85 * The theme registry.
Chris@0 86 */
Chris@0 87 public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, Registry $theme_registry = NULL) {
Chris@0 88 $this->entityTypeId = $entity_type->id();
Chris@0 89 $this->entityType = $entity_type;
Chris@0 90 $this->entityManager = $entity_manager;
Chris@0 91 $this->languageManager = $language_manager;
Chris@0 92 $this->themeRegistry = $theme_registry ?: \Drupal::service('theme.registry');
Chris@0 93 }
Chris@0 94
Chris@0 95 /**
Chris@0 96 * {@inheritdoc}
Chris@0 97 */
Chris@0 98 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
Chris@0 99 return new static(
Chris@0 100 $entity_type,
Chris@0 101 $container->get('entity.manager'),
Chris@0 102 $container->get('language_manager'),
Chris@0 103 $container->get('theme.registry')
Chris@0 104 );
Chris@0 105 }
Chris@0 106
Chris@0 107 /**
Chris@0 108 * {@inheritdoc}
Chris@0 109 */
Chris@0 110 public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
Chris@0 111 $build_list = $this->viewMultiple([$entity], $view_mode, $langcode);
Chris@0 112
Chris@0 113 // The default ::buildMultiple() #pre_render callback won't run, because we
Chris@0 114 // extract a child element of the default renderable array. Thus we must
Chris@0 115 // assign an alternative #pre_render callback that applies the necessary
Chris@0 116 // transformations and then still calls ::buildMultiple().
Chris@0 117 $build = $build_list[0];
Chris@0 118 $build['#pre_render'][] = [$this, 'build'];
Chris@0 119
Chris@0 120 return $build;
Chris@0 121 }
Chris@0 122
Chris@0 123 /**
Chris@0 124 * {@inheritdoc}
Chris@0 125 */
Chris@0 126 public function viewMultiple(array $entities = [], $view_mode = 'full', $langcode = NULL) {
Chris@0 127 $build_list = [
Chris@0 128 '#sorted' => TRUE,
Chris@0 129 '#pre_render' => [[$this, 'buildMultiple']],
Chris@0 130 ];
Chris@0 131 $weight = 0;
Chris@0 132 foreach ($entities as $key => $entity) {
Chris@0 133 // Ensure that from now on we are dealing with the proper translation
Chris@0 134 // object.
Chris@0 135 $entity = $this->entityManager->getTranslationFromContext($entity, $langcode);
Chris@0 136
Chris@0 137 // Set build defaults.
Chris@0 138 $build_list[$key] = $this->getBuildDefaults($entity, $view_mode);
Chris@0 139 $entityType = $this->entityTypeId;
Chris@0 140 $this->moduleHandler()->alter([$entityType . '_build_defaults', 'entity_build_defaults'], $build_list[$key], $entity, $view_mode);
Chris@0 141
Chris@0 142 $build_list[$key]['#weight'] = $weight++;
Chris@0 143 }
Chris@0 144
Chris@0 145 return $build_list;
Chris@0 146 }
Chris@0 147
Chris@0 148 /**
Chris@0 149 * Provides entity-specific defaults to the build process.
Chris@0 150 *
Chris@0 151 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@0 152 * The entity for which the defaults should be provided.
Chris@0 153 * @param string $view_mode
Chris@0 154 * The view mode that should be used.
Chris@0 155 *
Chris@0 156 * @return array
Chris@0 157 */
Chris@0 158 protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
Chris@0 159 // Allow modules to change the view mode.
Chris@0 160 $context = [];
Chris@0 161 $this->moduleHandler()->alter('entity_view_mode', $view_mode, $entity, $context);
Chris@0 162
Chris@0 163 $build = [
Chris@0 164 "#{$this->entityTypeId}" => $entity,
Chris@0 165 '#view_mode' => $view_mode,
Chris@0 166 // Collect cache defaults for this entity.
Chris@0 167 '#cache' => [
Chris@0 168 'tags' => Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags()),
Chris@0 169 'contexts' => $entity->getCacheContexts(),
Chris@0 170 'max-age' => $entity->getCacheMaxAge(),
Chris@0 171 ],
Chris@0 172 ];
Chris@0 173
Chris@0 174 // Add the default #theme key if a template exists for it.
Chris@0 175 if ($this->themeRegistry->getRuntime()->has($this->entityTypeId)) {
Chris@0 176 $build['#theme'] = $this->entityTypeId;
Chris@0 177 }
Chris@0 178
Chris@0 179 // Cache the rendered output if permitted by the view mode and global entity
Chris@0 180 // type configuration.
Chris@0 181 if ($this->isViewModeCacheable($view_mode) && !$entity->isNew() && $entity->isDefaultRevision() && $this->entityType->isRenderCacheable()) {
Chris@0 182 $build['#cache'] += [
Chris@0 183 'keys' => [
Chris@0 184 'entity_view',
Chris@0 185 $this->entityTypeId,
Chris@0 186 $entity->id(),
Chris@0 187 $view_mode,
Chris@0 188 ],
Chris@0 189 'bin' => $this->cacheBin,
Chris@0 190 ];
Chris@0 191
Chris@0 192 if ($entity instanceof TranslatableInterface && count($entity->getTranslationLanguages()) > 1) {
Chris@0 193 $build['#cache']['keys'][] = $entity->language()->getId();
Chris@0 194 }
Chris@0 195 }
Chris@0 196
Chris@0 197 return $build;
Chris@0 198 }
Chris@0 199
Chris@0 200 /**
Chris@0 201 * Builds an entity's view; augments entity defaults.
Chris@0 202 *
Chris@0 203 * This function is assigned as a #pre_render callback in ::view().
Chris@0 204 *
Chris@0 205 * It transforms the renderable array for a single entity to the same
Chris@0 206 * structure as if we were rendering multiple entities, and then calls the
Chris@0 207 * default ::buildMultiple() #pre_render callback.
Chris@0 208 *
Chris@0 209 * @param array $build
Chris@0 210 * A renderable array containing build information and context for an entity
Chris@0 211 * view.
Chris@0 212 *
Chris@0 213 * @return array
Chris@0 214 * The updated renderable array.
Chris@0 215 *
Chris@0 216 * @see drupal_render()
Chris@0 217 */
Chris@0 218 public function build(array $build) {
Chris@0 219 $build_list = [$build];
Chris@0 220 $build_list = $this->buildMultiple($build_list);
Chris@0 221 return $build_list[0];
Chris@0 222 }
Chris@0 223
Chris@0 224 /**
Chris@0 225 * Builds multiple entities' views; augments entity defaults.
Chris@0 226 *
Chris@0 227 * This function is assigned as a #pre_render callback in ::viewMultiple().
Chris@0 228 *
Chris@0 229 * By delaying the building of an entity until the #pre_render processing in
Chris@0 230 * drupal_render(), the processing cost of assembling an entity's renderable
Chris@0 231 * array is saved on cache-hit requests.
Chris@0 232 *
Chris@0 233 * @param array $build_list
Chris@0 234 * A renderable array containing build information and context for an
Chris@0 235 * entity view.
Chris@0 236 *
Chris@0 237 * @return array
Chris@0 238 * The updated renderable array.
Chris@0 239 *
Chris@0 240 * @see drupal_render()
Chris@0 241 */
Chris@0 242 public function buildMultiple(array $build_list) {
Chris@0 243 // Build the view modes and display objects.
Chris@0 244 $view_modes = [];
Chris@0 245 $entity_type_key = "#{$this->entityTypeId}";
Chris@0 246 $view_hook = "{$this->entityTypeId}_view";
Chris@0 247
Chris@0 248 // Find the keys for the ContentEntities in the build; Store entities for
Chris@0 249 // rendering by view_mode.
Chris@0 250 $children = Element::children($build_list);
Chris@0 251 foreach ($children as $key) {
Chris@0 252 if (isset($build_list[$key][$entity_type_key])) {
Chris@0 253 $entity = $build_list[$key][$entity_type_key];
Chris@0 254 if ($entity instanceof FieldableEntityInterface) {
Chris@0 255 $view_modes[$build_list[$key]['#view_mode']][$key] = $entity;
Chris@0 256 }
Chris@0 257 }
Chris@0 258 }
Chris@0 259
Chris@0 260 // Build content for the displays represented by the entities.
Chris@0 261 foreach ($view_modes as $view_mode => $view_mode_entities) {
Chris@0 262 $displays = EntityViewDisplay::collectRenderDisplays($view_mode_entities, $view_mode);
Chris@0 263 $this->buildComponents($build_list, $view_mode_entities, $displays, $view_mode);
Chris@0 264 foreach (array_keys($view_mode_entities) as $key) {
Chris@0 265 // Allow for alterations while building, before rendering.
Chris@0 266 $entity = $build_list[$key][$entity_type_key];
Chris@0 267 $display = $displays[$entity->bundle()];
Chris@0 268
Chris@0 269 $this->moduleHandler()->invokeAll($view_hook, [&$build_list[$key], $entity, $display, $view_mode]);
Chris@0 270 $this->moduleHandler()->invokeAll('entity_view', [&$build_list[$key], $entity, $display, $view_mode]);
Chris@0 271
Chris@0 272 $this->alterBuild($build_list[$key], $entity, $display, $view_mode);
Chris@0 273
Chris@0 274 // Assign the weights configured in the display.
Chris@0 275 // @todo: Once https://www.drupal.org/node/1875974 provides the missing
Chris@0 276 // API, only do it for 'extra fields', since other components have
Chris@0 277 // been taken care of in EntityViewDisplay::buildMultiple().
Chris@0 278 foreach ($display->getComponents() as $name => $options) {
Chris@0 279 if (isset($build_list[$key][$name])) {
Chris@0 280 $build_list[$key][$name]['#weight'] = $options['weight'];
Chris@0 281 }
Chris@0 282 }
Chris@0 283
Chris@0 284 // Allow modules to modify the render array.
Chris@0 285 $this->moduleHandler()->alter([$view_hook, 'entity_view'], $build_list[$key], $entity, $display);
Chris@0 286 }
Chris@0 287 }
Chris@0 288
Chris@0 289 return $build_list;
Chris@0 290 }
Chris@0 291
Chris@0 292 /**
Chris@0 293 * {@inheritdoc}
Chris@0 294 */
Chris@0 295 public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
Chris@0 296 $entities_by_bundle = [];
Chris@0 297 foreach ($entities as $id => $entity) {
Chris@0 298 // Initialize the field item attributes for the fields being displayed.
Chris@0 299 // The entity can include fields that are not displayed, and the display
Chris@0 300 // can include components that are not fields, so we want to act on the
Chris@0 301 // intersection. However, the entity can have many more fields than are
Chris@0 302 // displayed, so we avoid the cost of calling $entity->getProperties()
Chris@0 303 // by iterating the intersection as follows.
Chris@0 304 foreach ($displays[$entity->bundle()]->getComponents() as $name => $options) {
Chris@0 305 if ($entity->hasField($name)) {
Chris@0 306 foreach ($entity->get($name) as $item) {
Chris@0 307 $item->_attributes = [];
Chris@0 308 }
Chris@0 309 }
Chris@0 310 }
Chris@0 311 // Group the entities by bundle.
Chris@0 312 $entities_by_bundle[$entity->bundle()][$id] = $entity;
Chris@0 313 }
Chris@0 314
Chris@0 315 // Invoke hook_entity_prepare_view().
Chris@0 316 $this->moduleHandler()->invokeAll('entity_prepare_view', [$this->entityTypeId, $entities, $displays, $view_mode]);
Chris@0 317
Chris@0 318 // Let the displays build their render arrays.
Chris@0 319 foreach ($entities_by_bundle as $bundle => $bundle_entities) {
Chris@0 320 $display_build = $displays[$bundle]->buildMultiple($bundle_entities);
Chris@0 321 foreach ($bundle_entities as $id => $entity) {
Chris@0 322 $build[$id] += $display_build[$id];
Chris@0 323 }
Chris@0 324 }
Chris@0 325 }
Chris@0 326
Chris@0 327 /**
Chris@0 328 * Specific per-entity building.
Chris@0 329 *
Chris@0 330 * @param array $build
Chris@0 331 * The render array that is being created.
Chris@0 332 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@0 333 * The entity to be prepared.
Chris@0 334 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
Chris@0 335 * The entity view display holding the display options configured for the
Chris@0 336 * entity components.
Chris@0 337 * @param string $view_mode
Chris@0 338 * The view mode that should be used to prepare the entity.
Chris@0 339 */
Chris@0 340 protected function alterBuild(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {}
Chris@0 341
Chris@0 342 /**
Chris@0 343 * {@inheritdoc}
Chris@0 344 */
Chris@0 345 public function getCacheTags() {
Chris@0 346 return [$this->entityTypeId . '_view'];
Chris@0 347 }
Chris@0 348
Chris@0 349 /**
Chris@0 350 * {@inheritdoc}
Chris@0 351 */
Chris@0 352 public function resetCache(array $entities = NULL) {
Chris@0 353 // If no set of specific entities is provided, invalidate the entity view
Chris@0 354 // builder's cache tag. This will invalidate all entities rendered by this
Chris@0 355 // view builder.
Chris@0 356 // Otherwise, if a set of specific entities is provided, invalidate those
Chris@0 357 // specific entities only, plus their list cache tags, because any lists in
Chris@0 358 // which these entities are rendered, must be invalidated as well. However,
Chris@0 359 // even in this case, we might invalidate more cache items than necessary.
Chris@0 360 // When we have a way to invalidate only those cache items that have both
Chris@0 361 // the individual entity's cache tag and the view builder's cache tag, we'll
Chris@0 362 // be able to optimize this further.
Chris@0 363 if (isset($entities)) {
Chris@0 364 $tags = [];
Chris@0 365 foreach ($entities as $entity) {
Chris@0 366 $tags = Cache::mergeTags($tags, $entity->getCacheTags());
Chris@0 367 $tags = Cache::mergeTags($tags, $entity->getEntityType()->getListCacheTags());
Chris@0 368 }
Chris@0 369 Cache::invalidateTags($tags);
Chris@0 370 }
Chris@0 371 else {
Chris@0 372 Cache::invalidateTags($this->getCacheTags());
Chris@0 373 }
Chris@0 374 }
Chris@0 375
Chris@0 376 /**
Chris@0 377 * Determines whether the view mode is cacheable.
Chris@0 378 *
Chris@0 379 * @param string $view_mode
Chris@0 380 * Name of the view mode that should be rendered.
Chris@0 381 *
Chris@0 382 * @return bool
Chris@0 383 * TRUE if the view mode can be cached, FALSE otherwise.
Chris@0 384 */
Chris@0 385 protected function isViewModeCacheable($view_mode) {
Chris@0 386 if ($view_mode == 'default') {
Chris@0 387 // The 'default' is not an actual view mode.
Chris@0 388 return TRUE;
Chris@0 389 }
Chris@0 390 $view_modes_info = $this->entityManager->getViewModes($this->entityTypeId);
Chris@0 391 return !empty($view_modes_info[$view_mode]['cache']);
Chris@0 392 }
Chris@0 393
Chris@0 394 /**
Chris@0 395 * {@inheritdoc}
Chris@0 396 */
Chris@0 397 public function viewField(FieldItemListInterface $items, $display_options = []) {
Chris@0 398 $entity = $items->getEntity();
Chris@0 399 $field_name = $items->getFieldDefinition()->getName();
Chris@0 400 $display = $this->getSingleFieldDisplay($entity, $field_name, $display_options);
Chris@0 401
Chris@0 402 $output = [];
Chris@0 403 $build = $display->build($entity);
Chris@0 404 if (isset($build[$field_name])) {
Chris@0 405 $output = $build[$field_name];
Chris@0 406 }
Chris@0 407
Chris@0 408 return $output;
Chris@0 409 }
Chris@0 410
Chris@0 411 /**
Chris@0 412 * {@inheritdoc}
Chris@0 413 */
Chris@0 414 public function viewFieldItem(FieldItemInterface $item, $display = []) {
Chris@0 415 $entity = $item->getEntity();
Chris@0 416 $field_name = $item->getFieldDefinition()->getName();
Chris@0 417
Chris@0 418 // Clone the entity since we are going to modify field values.
Chris@0 419 $clone = clone $entity;
Chris@0 420
Chris@0 421 // Push the item as the single value for the field, and defer to viewField()
Chris@0 422 // to build the render array for the whole list.
Chris@0 423 $clone->{$field_name}->setValue([$item->getValue()]);
Chris@0 424 $elements = $this->viewField($clone->{$field_name}, $display);
Chris@0 425
Chris@0 426 // Extract the part of the render array we need.
Chris@0 427 $output = isset($elements[0]) ? $elements[0] : [];
Chris@0 428 if (isset($elements['#access'])) {
Chris@0 429 $output['#access'] = $elements['#access'];
Chris@0 430 }
Chris@0 431
Chris@0 432 return $output;
Chris@0 433 }
Chris@0 434
Chris@0 435 /**
Chris@0 436 * Gets an EntityViewDisplay for rendering an individual field.
Chris@0 437 *
Chris@0 438 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@0 439 * The entity.
Chris@0 440 * @param string $field_name
Chris@0 441 * The field name.
Chris@0 442 * @param string|array $display_options
Chris@0 443 * The display options passed to the viewField() method.
Chris@0 444 *
Chris@0 445 * @return \Drupal\Core\Entity\Display\EntityViewDisplayInterface
Chris@0 446 */
Chris@0 447 protected function getSingleFieldDisplay($entity, $field_name, $display_options) {
Chris@0 448 if (is_string($display_options)) {
Chris@0 449 // View mode: use the Display configured for the view mode.
Chris@0 450 $view_mode = $display_options;
Chris@0 451 $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
Chris@0 452 // Hide all fields except the current one.
Chris@0 453 foreach (array_keys($entity->getFieldDefinitions()) as $name) {
Chris@0 454 if ($name != $field_name) {
Chris@0 455 $display->removeComponent($name);
Chris@0 456 }
Chris@0 457 }
Chris@0 458 }
Chris@0 459 else {
Chris@0 460 // Array of custom display options: use a runtime Display for the
Chris@0 461 // '_custom' view mode. Persist the displays created, to reduce the number
Chris@0 462 // of objects (displays and formatter plugins) created when rendering a
Chris@0 463 // series of fields individually for cases such as views tables.
Chris@0 464 $entity_type_id = $entity->getEntityTypeId();
Chris@0 465 $bundle = $entity->bundle();
Chris@0 466 $key = $entity_type_id . ':' . $bundle . ':' . $field_name . ':' . Crypt::hashBase64(serialize($display_options));
Chris@0 467 if (!isset($this->singleFieldDisplays[$key])) {
Chris@0 468 $this->singleFieldDisplays[$key] = EntityViewDisplay::create([
Chris@0 469 'targetEntityType' => $entity_type_id,
Chris@0 470 'bundle' => $bundle,
Chris@0 471 'status' => TRUE,
Chris@0 472 ])->setComponent($field_name, $display_options);
Chris@0 473 }
Chris@0 474 $display = $this->singleFieldDisplays[$key];
Chris@0 475 }
Chris@0 476
Chris@0 477 return $display;
Chris@0 478 }
Chris@0 479
Chris@0 480 }