You are here

public function BlockRepository::getVisibleBlocksPerRegion in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/block/src/BlockRepository.php \Drupal\block\BlockRepository::getVisibleBlocksPerRegion()

Returns an array of regions and their block entities.

Parameters

\Drupal\Core\Cache\CacheableMetadata[] $cacheable_metadata: (optional) List of CacheableMetadata objects, keyed by region. This is by reference and is used to pass this information back to the caller.

Return value

array The array is first keyed by region machine name, with the values containing an array keyed by block ID, with block entities as the values.

Overrides BlockRepositoryInterface::getVisibleBlocksPerRegion

File

core/modules/block/src/BlockRepository.php, line 48

Class

BlockRepository
Provides a repository for Block config entities.

Namespace

Drupal\block

Code

public function getVisibleBlocksPerRegion(array &$cacheable_metadata = []) {
  $active_theme = $this->themeManager
    ->getActiveTheme();

  // Build an array of the region names in the right order.
  $empty = array_fill_keys($active_theme
    ->getRegions(), []);
  $full = [];
  foreach ($this->blockStorage
    ->loadByProperties([
    'theme' => $active_theme
      ->getName(),
  ]) as $block_id => $block) {

    /** @var \Drupal\block\BlockInterface $block */
    $access = $block
      ->access('view', NULL, TRUE);
    $region = $block
      ->getRegion();
    if (!isset($cacheable_metadata[$region])) {
      $cacheable_metadata[$region] = CacheableMetadata::createFromObject($access);
    }
    else {
      $cacheable_metadata[$region] = $cacheable_metadata[$region]
        ->merge(CacheableMetadata::createFromObject($access));
    }

    // Set the contexts on the block before checking access.
    if ($access
      ->isAllowed()) {
      $full[$region][$block_id] = $block;
    }
  }

  // Merge it with the actual values to maintain the region ordering.
  $assignments = array_intersect_key(array_merge($empty, $full), $empty);
  foreach ($assignments as &$assignment) {

    // Suppress errors because PHPUnit will indirectly modify the contents,
    // triggering https://bugs.php.net/bug.php?id=50688.
    @uasort($assignment, 'Drupal\\block\\Entity\\Block::sort');
  }
  return $assignments;
}