BlockPreviewRenderer.php in Panopoly Magic 8.2
File
src/BlockPreviewRenderer.php
View source
<?php
namespace Drupal\panopoly_magic;
use Drupal\block_content\Entity\BlockContent;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class BlockPreviewRenderer {
use StringTranslationTrait;
protected $blockManager;
protected $contextHandler;
public function __construct(BlockManagerInterface $block_manager, ContextHandlerInterface $context_handler) {
$this->blockManager = $block_manager;
$this->contextHandler = $context_handler;
}
public function buildBlockPreview($block_id, array $contexts = []) {
$block_definition = $this->blockManager
->getDefinition($block_id);
$block_plugin = $this->blockManager
->createInstance($block_id);
if ($block_plugin instanceof ContextAwarePluginInterface) {
$mapping = $block_plugin
->getContextMapping();
foreach ($block_plugin
->getContextDefinitions() as $context_slot => $definition) {
if (isset($mapping[$context_slot])) {
continue;
}
if ($definition
->isRequired()) {
$valid_contexts = $this->contextHandler
->getMatchingContexts($contexts, $definition);
if (count($valid_contexts) > 0) {
$valid_context_ids = array_keys($valid_contexts);
$mapping[$context_slot] = $valid_context_ids[0];
}
}
}
try {
$this->contextHandler
->applyContextMapping($block_plugin, $contexts, $mapping);
} catch (ContextException $e) {
return [
'#markup' => $this
->t("Missing required context"),
];
}
}
if (!empty($block_definition['preview_settings']) && is_array($block_definition['preview_settings'])) {
if ($block_plugin
->getBaseId() === 'inline_block') {
$block_definition['preview_settings']['type'] = $block_plugin
->getDerivativeId();
$block_entity = BlockContent::create($block_definition['preview_settings']);
$block_plugin
->setConfiguration([
'block_serialized' => serialize($block_entity),
]);
}
else {
$block_plugin
->setConfiguration(array_merge($block_plugin
->getConfiguration(), $block_definition['preview_settings']));
}
}
try {
if (!empty($block_definition['preview_callback']) && is_callable($block_definition['preview_callback'])) {
return call_user_func($block_definition['preview_callback'], $block_plugin);
}
if (!empty($block_definition['preview_image'])) {
$preview_image = [
'#theme' => 'image',
'#uri' => $block_definition['preview_image'],
];
if (!empty($block_definition['preview_alt'])) {
$preview_image['#alt'] = $block_definition['preview_alt'];
}
return $preview_image;
}
if ($block_plugin instanceof BlockPreviewInterface) {
return $block_plugin
->buildPreview();
}
return $block_plugin
->build();
} catch (ContextException $e) {
return [
'#markup' => $this
->t("Missing required context"),
];
}
}
}