BlockVariantTrait.php in Chaos Tool Suite (ctools) 8.3
File
src/Plugin/BlockVariantTrait.php
View source
<?php
namespace Drupal\ctools\Plugin;
use Drupal\ctools\Event\BlockVariantEvent;
use Drupal\ctools\Event\BlockVariantEvents;
trait BlockVariantTrait {
protected $blockManager;
protected $blockPluginCollection;
protected $eventDispatcher;
public abstract function getRegionNames();
public function getBlock($block_id) {
return $this
->getBlockCollection()
->get($block_id);
}
public function addBlock(array $configuration) {
$configuration['uuid'] = $this
->uuidGenerator()
->generate();
$this
->getBlockCollection()
->addInstanceId($configuration['uuid'], $configuration);
$block = $this
->getBlock($configuration['uuid']);
$event = new BlockVariantEvent($block, $this);
$this
->eventDispatcher()
->dispatch(BlockVariantEvents::ADD_BLOCK, $event);
return $configuration['uuid'];
}
public function removeBlock($block_id) {
$block = $this
->getBlock($block_id);
$this
->getBlockCollection()
->removeInstanceId($block_id);
$event = new BlockVariantEvent($block, $this);
$this
->eventDispatcher()
->dispatch(BlockVariantEvents::DELETE_BLOCK, $event);
return $this;
}
public function updateBlock($block_id, array $configuration) {
$block = $this
->getBlock($block_id);
$existing_configuration = $block
->getConfiguration();
$this
->getBlockCollection()
->setInstanceConfiguration($block_id, $configuration + $existing_configuration);
$event = new BlockVariantEvent($block, $this);
$this
->eventDispatcher()
->dispatch(BlockVariantEvents::UPDATE_BLOCK, $event);
return $this;
}
public function getRegionAssignment($block_id) {
$configuration = $this
->getBlock($block_id)
->getConfiguration();
return isset($configuration['region']) ? $configuration['region'] : NULL;
}
public function getRegionAssignments() {
$empty = array_fill_keys(array_keys($this
->getRegionNames()), []);
$full = $this
->getBlockCollection()
->getAllByRegion();
return array_intersect_key(array_merge($empty, $full), $empty);
}
public function getRegionName($region) {
$regions = $this
->getRegionNames();
return isset($regions[$region]) ? $regions[$region] : '';
}
protected function getBlockManager() {
if (!$this->blockManager) {
$this->blockManager = \Drupal::service('plugin.manager.block');
}
return $this->blockManager;
}
protected function getBlockCollection() {
if (!$this->blockPluginCollection) {
$this->blockPluginCollection = new BlockPluginCollection($this
->getBlockManager(), $this
->getBlockConfig());
}
return $this->blockPluginCollection;
}
protected function eventDispatcher() {
if (!$this->eventDispatcher) {
$this->eventDispatcher = \Drupal::service('event_dispatcher');
}
return $this->eventDispatcher;
}
protected abstract function uuidGenerator();
protected abstract function getBlockConfig();
}