EntityViewTrait.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. * @return array
  30. *
  31. * @see drupal_render()
  32. */
  33. protected function buildEntityView(EntityInterface $entity, $view_mode = 'full', $langcode = NULL, $reset = FALSE) {
  34. $ensure_fully_built = function (&$elements) use (&$ensure_fully_built) {
  35. // If the default values for this element have not been loaded yet, populate
  36. // them.
  37. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  38. $elements += \Drupal::service('element_info')->getInfo($elements['#type']);
  39. }
  40. // Make any final changes to the element before it is rendered. This means
  41. // that the $element or the children can be altered or corrected before the
  42. // element is rendered into the final text.
  43. if (isset($elements['#pre_render'])) {
  44. foreach ($elements['#pre_render'] as $callable) {
  45. $elements = call_user_func($callable, $elements);
  46. }
  47. }
  48. // And recurse.
  49. $children = Element::children($elements, TRUE);
  50. foreach ($children as $key) {
  51. $ensure_fully_built($elements[$key]);
  52. }
  53. };
  54. $render_controller = $this->container->get('entity.manager')->getViewBuilder($entity->getEntityTypeId());
  55. if ($reset) {
  56. $render_controller->resetCache([$entity->id()]);
  57. }
  58. $build = $render_controller->view($entity, $view_mode, $langcode);
  59. $ensure_fully_built($build);
  60. return $build;
  61. }
  62. }