3 namespace Drupal\block;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Plugin\Context\ContextHandlerInterface;
8 use Drupal\Core\Theme\ThemeManagerInterface;
11 * Provides a repository for Block config entities.
13 class BlockRepository implements BlockRepositoryInterface {
18 * @var \Drupal\Core\Entity\EntityStorageInterface
20 protected $blockStorage;
25 * @var \Drupal\Core\Theme\ThemeManagerInterface
27 protected $themeManager;
30 * Constructs a new BlockRepository.
32 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
34 * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
36 * @param \Drupal\Core\Plugin\Context\ContextHandlerInterface $context_handler
37 * The plugin context handler.
39 public function __construct(EntityManagerInterface $entity_manager, ThemeManagerInterface $theme_manager, ContextHandlerInterface $context_handler) {
40 $this->blockStorage = $entity_manager->getStorage('block');
41 $this->themeManager = $theme_manager;
42 $this->contextHandler = $context_handler;
48 public function getVisibleBlocksPerRegion(array &$cacheable_metadata = []) {
49 $active_theme = $this->themeManager->getActiveTheme();
50 // Build an array of the region names in the right order.
51 $empty = array_fill_keys($active_theme->getRegions(), []);
54 foreach ($this->blockStorage->loadByProperties(['theme' => $active_theme->getName()]) as $block_id => $block) {
55 /** @var \Drupal\block\BlockInterface $block */
56 $access = $block->access('view', NULL, TRUE);
57 $region = $block->getRegion();
58 if (!isset($cacheable_metadata[$region])) {
59 $cacheable_metadata[$region] = CacheableMetadata::createFromObject($access);
62 $cacheable_metadata[$region] = $cacheable_metadata[$region]->merge(CacheableMetadata::createFromObject($access));
65 // Set the contexts on the block before checking access.
66 if ($access->isAllowed()) {
67 $full[$region][$block_id] = $block;
71 // Merge it with the actual values to maintain the region ordering.
72 $assignments = array_intersect_key(array_merge($empty, $full), $empty);
73 foreach ($assignments as &$assignment) {
74 // Suppress errors because PHPUnit will indirectly modify the contents,
75 // triggering https://bugs.php.net/bug.php?id=50688.
76 @uasort($assignment, 'Drupal\block\Entity\Block::sort');