<?php

namespace Drupal\pagedesigner_block;

use Drupal\block\BlockRepository as CoreBlockRepository;
use Drupal\Core\Cache\CacheableMetadata;

/**
 * Extend core Blockrepository to remove pagedesigner blocks from page list.
 */
class BlockRepository extends CoreBlockRepository {

  /**
   * {@inheritdoc}
   *
   * Remove pagedesigner region.
   */
  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 */
      $region = $block->getRegion();
      if ($region != 'pagedesigner') {
        $access = $block->access('view', NULL, TRUE);
        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) {
      uasort($assignment, 'Drupal\block\Entity\Block::sort');
    }
    return $assignments;
  }

}
