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