View source
<?php
namespace Drupal\block_blacklist;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class Blacklist extends ServiceProviderBase {
protected $entityTypeManager;
protected $match;
protected $prefix;
protected $regex;
protected $hasSettings;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function setUp($settings) {
$this->match = !empty($settings) ? trim($settings['match']) : '';
$this->prefix = !empty($settings) ? trim($settings['prefix']) : '';
$this->regex = !empty($settings) ? trim($settings['regex']) : '';
$this->hasSettings = !empty($this->match . $this->prefix . $this->regex);
}
public function hasSettings() {
return $this->hasSettings;
}
public function blockIsAllowed($plugin_id) {
static $block_is_blacklisted, $blocks_in_use = [];
if (!$this->hasSettings) {
return TRUE;
}
if (!isset($block_is_blacklisted)) {
foreach ($this->entityTypeManager
->getStorage('entity_view_display')
->loadMultiple() as $entity_view_display) {
foreach ($entity_view_display
->getThirdPartySetting('layout_builder', 'sections', []) as $section) {
foreach ($section
->getComponents() as $component) {
$blocks_in_use[] = $component
->getPluginId();
}
}
}
$block_is_blacklisted = 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;
}
}
};
}
return in_array($plugin_id, $blocks_in_use) || !$block_is_blacklisted($plugin_id);
}
}