EntityViewTrait.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Drupal\Tests;
  3. use Drupal\Core\Entity\EntityInterface;
  4. use Drupal\Core\Render\Element;
  5. /**
  6. * Provides helper methods to deal with building entity views in tests.
  7. */
  8. trait EntityViewTrait {
  9. /**
  10. * Builds the renderable view of an entity.
  11. *
  12. * Entities postpone the composition of their renderable arrays to #pre_render
  13. * functions in order to maximize cache efficacy. This means that the full
  14. * renderable array for an entity is constructed in drupal_render(). Some
  15. * tests require the complete renderable array for an entity outside of the
  16. * drupal_render process in order to verify the presence of specific values.
  17. * This method isolates the steps in the render process that produce an
  18. * entity's renderable array.
  19. *
  20. * @param \Drupal\Core\Entity\EntityInterface $entity
  21. * The entity to prepare a renderable array for.
  22. * @param string $view_mode
  23. * (optional) The view mode that should be used to build the entity.
  24. * @param null $langcode
  25. * (optional) For which language the entity should be prepared, defaults to
  26. * the current content language.
  27. * @param bool $reset
  28. * (optional) Whether to clear the cache for this entity.
  29. *
  30. * @return array
  31. *
  32. * @see \Drupal\Core\Render\RendererInterface::render()
  33. */
  34. protected function buildEntityView(EntityInterface $entity, $view_mode = 'full', $langcode = NULL, $reset = FALSE) {
  35. $ensure_fully_built = function (&$elements) use (&$ensure_fully_built) {
  36. // If the default values for this element have not been loaded yet, populate
  37. // them.
  38. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  39. $elements += \Drupal::service('element_info')->getInfo($elements['#type']);
  40. }
  41. // Make any final changes to the element before it is rendered. This means
  42. // that the $element or the children can be altered or corrected before the
  43. // element is rendered into the final text.
  44. if (isset($elements['#pre_render'])) {
  45. foreach ($elements['#pre_render'] as $callable) {
  46. $elements = call_user_func($callable, $elements);
  47. }
  48. }
  49. // And recurse.
  50. $children = Element::children($elements, TRUE);
  51. foreach ($children as $key) {
  52. $ensure_fully_built($elements[$key]);
  53. }
  54. };
  55. $render_controller = $this->container->get('entity_type.manager')->getViewBuilder($entity->getEntityTypeId());
  56. if ($reset) {
  57. $render_controller->resetCache([$entity->id()]);
  58. }
  59. $build = $render_controller->view($entity, $view_mode, $langcode);
  60. $ensure_fully_built($build);
  61. return $build;
  62. }
  63. }