Namespace
Drupal\ctools\Plugin
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;
abstract public 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($event, BlockVariantEvents::ADD_BLOCK);
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($event, BlockVariantEvents::DELETE_BLOCK);
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($event, BlockVariantEvents::UPDATE_BLOCK);
return $this;
}
public function getRegionAssignment($block_id) {
$configuration = $this->getBlock($block_id)
->getConfiguration();
return $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 $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;
}
abstract protected function uuidGenerator();
abstract protected function getBlockConfig();
}
Traits
| Title |
Deprecated |
Summary |
| BlockVariantTrait |
|
Provides methods for \Drupal\ctools\Plugin\BlockVariantInterface. |