You are here

public function RenderCache::getCacheableRenderArray in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Render/RenderCache.php \Drupal\Core\Render\RenderCache::getCacheableRenderArray()
  2. 9 core/lib/Drupal/Core/Render/RenderCache.php \Drupal\Core\Render\RenderCache::getCacheableRenderArray()

File

core/lib/Drupal/Core/Render/RenderCache.php, line 331

Class

RenderCache
Wraps the caching logic for the render caching system.

Namespace

Drupal\Core\Render

Code

public function getCacheableRenderArray(array $elements) {
  $data = [
    '#markup' => $elements['#markup'],
    '#attached' => $elements['#attached'],
    '#cache' => [
      'contexts' => $elements['#cache']['contexts'],
      'tags' => $elements['#cache']['tags'],
      'max-age' => $elements['#cache']['max-age'],
    ],
  ];

  // Preserve cacheable items if specified. If we are preserving any cacheable
  // children of the element, we assume we are only interested in their
  // individual markup and not the parent's one, thus we empty it to minimize
  // the cache entry size.
  if (!empty($elements['#cache_properties']) && is_array($elements['#cache_properties'])) {
    $data['#cache_properties'] = $elements['#cache_properties'];

    // Extract all the cacheable items from the element using cache
    // properties.
    $cacheable_items = array_intersect_key($elements, array_flip($elements['#cache_properties']));
    $cacheable_children = Element::children($cacheable_items);
    if ($cacheable_children) {
      $data['#markup'] = '';

      // Cache only cacheable children's markup.
      foreach ($cacheable_children as $key) {

        // We can assume that #markup is safe at this point.
        $cacheable_items[$key] = [
          '#markup' => Markup::create($cacheable_items[$key]['#markup']),
        ];
      }
    }
    $data += $cacheable_items;
  }
  $data['#markup'] = Markup::create($data['#markup']);
  return $data;
}