You are here

public function BlockListOverride::blockIsAllowed in Block List Override 1.0.x

Determines whether the given block plugin is allowed or not.

Parameters

string $plugin_id: The block plugin ID to check.

Return value

bool TRUE if the block is allowed, FALSE otherwise.

File

src/BlockListOverride.php, line 92

Class

BlockListOverride
Service to remove blocks from a list.

Namespace

Drupal\block_list_override

Code

public function blockIsAllowed($plugin_id) {
  static $block_is_listed, $blocks_in_use = [];
  if (!$this->hasSettings) {
    return TRUE;
  }

  // See which blocks are in use in Layout builder. We must not remove any
  // Layout Builder blocks that are already in use.
  if (!isset($block_is_listed)) {
    foreach ($this->entityTypeManager
      ->getStorage('entity_view_display')
      ->loadMultiple() as $entity_view_display) {

      // Look for block plugins in each Layout Builder section.

      /** @var \Drupal\layout_builder\Section $section */
      foreach ($entity_view_display
        ->getThirdPartySetting('layout_builder', 'sections', []) as $section) {

        /** @var \Drupal\layout_builder\SectionComponent $component */
        foreach ($section
          ->getComponents() as $component) {
          $blocks_in_use[] = $component
            ->getPluginId();
        }
      }
    }

    // Define a helper function.
    $block_is_listed = function ($plugin_id) {
      $list = explode("\n", $this->prefix);
      foreach ($list as $prefix) {
        $prefix = trim($prefix);
        if (!empty($prefix) && strpos($plugin_id, "{$prefix}:") === 0) {
          return TRUE;
        }
      }
      $list = explode("\n", $this->match);
      foreach ($list as $match) {
        $match = trim($match);
        if (!empty($match) && $plugin_id == $match) {
          return TRUE;
        }
      }
      $list = explode("\n", $this->regex);
      foreach ($list as $regex) {
        $regex = trim($regex);
        if (!empty($regex) && preg_match($regex, $plugin_id, $parts)) {
          return TRUE;
        }
      }
    };
  }

  // (Dis)allow the block if it is not in the list, or if it's already in use.
  if ($this->isNegated) {
    return in_array($plugin_id, $blocks_in_use) || $block_is_listed($plugin_id);
  }
  return in_array($plugin_id, $blocks_in_use) || !$block_is_listed($plugin_id);
}