You are here

class PageBlockDisplayVariant in Page Manager 8

Same name and namespace in other branches
  1. 8.4 src/Plugin/DisplayVariant/PageBlockDisplayVariant.php \Drupal\page_manager\Plugin\DisplayVariant\PageBlockDisplayVariant

Provides a variant plugin that simply contains blocks.

Plugin annotation


@DisplayVariant(
  id = "block_display",
  admin_label = @Translation("Block page")
)

Hierarchy

Expanded class hierarchy of PageBlockDisplayVariant

2 files declare their use of PageBlockDisplayVariant
PageBlockDisplayVariantTest.php in tests/src/Unit/PageBlockDisplayVariantTest.php
Contains \Drupal\Tests\page_manager\Unit\PageBlockDisplayVariantTest.
SerializationTest.php in tests/src/Kernel/SerializationTest.php
Contains \Drupal\Tests\page_manager\Kernel\SerializationTest.

File

src/Plugin/DisplayVariant/PageBlockDisplayVariant.php, line 38
Contains \Drupal\page_manager\Plugin\DisplayVariant\PageBlockDisplayVariant.

Namespace

Drupal\page_manager\Plugin\DisplayVariant
View source
class PageBlockDisplayVariant extends BlockDisplayVariant implements PluginWizardInterface {

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs a new BlockDisplayVariant.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Plugin\Context\ContextHandlerInterface $context_handler
   *   The context handler.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Component\Uuid\UuidInterface $uuid_generator
   *   The UUID generator.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Block\BlockManager $block_manager
   *   The block manager.
   * @param \Drupal\Core\Condition\ConditionManager $condition_manager
   *   The condition manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ContextHandlerInterface $context_handler, AccountInterface $account, UuidInterface $uuid_generator, Token $token, BlockManager $block_manager, ConditionManager $condition_manager, ModuleHandlerInterface $module_handler) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $context_handler, $account, $uuid_generator, $token, $block_manager, $condition_manager);
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('context.handler'), $container
      ->get('current_user'), $container
      ->get('uuid'), $container
      ->get('token'), $container
      ->get('plugin.manager.block'), $container
      ->get('plugin.manager.condition'), $container
      ->get('module_handler'));
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Set default page cache keys that include the display.
    $build['#cache']['keys'] = [
      'page_manager_block_display',
      $this
        ->id(),
    ];
    $build['#pre_render'][] = [
      $this,
      'buildRegions',
    ];
    return $build;
  }

  /**
   * #pre_render callback for building the regions.
   */
  public function buildRegions(array $build) {
    $cacheability = CacheableMetadata::createFromRenderArray($build)
      ->addCacheableDependency($this);
    $contexts = $this
      ->getContexts();
    foreach ($this
      ->getRegionAssignments() as $region => $blocks) {
      if (!$blocks) {
        continue;
      }
      $region_name = Html::getClass("block-region-{$region}");
      $build[$region]['#prefix'] = '<div class="' . $region_name . '">';
      $build[$region]['#suffix'] = '</div>';

      /** @var \Drupal\Core\Block\BlockPluginInterface[] $blocks */
      $weight = 0;
      foreach ($blocks as $block_id => $block) {
        if ($block instanceof ContextAwarePluginInterface) {
          $this
            ->contextHandler()
            ->applyContextMapping($block, $contexts);
        }
        $access = $block
          ->access($this->account, TRUE);
        $cacheability
          ->addCacheableDependency($access);
        if (!$access
          ->isAllowed()) {
          continue;
        }
        $block_build = [
          '#theme' => 'block',
          '#attributes' => [],
          '#weight' => $weight++,
          '#configuration' => $block
            ->getConfiguration(),
          '#plugin_id' => $block
            ->getPluginId(),
          '#base_plugin_id' => $block
            ->getBaseId(),
          '#derivative_plugin_id' => $block
            ->getDerivativeId(),
          '#block_plugin' => $block,
          '#pre_render' => [
            [
              $this,
              'buildBlock',
            ],
          ],
          '#cache' => [
            'keys' => [
              'page_manager_block_display',
              $this
                ->id(),
              'block',
              $block_id,
            ],
            // Each block needs cache tags of the page and the block plugin, as
            // only the page is a config entity that will trigger cache tag
            // invalidations in case of block configuration changes.
            'tags' => Cache::mergeTags($this
              ->getCacheTags(), $block
              ->getCacheTags()),
            'contexts' => $block
              ->getCacheContexts(),
            'max-age' => $block
              ->getCacheMaxAge(),
          ],
        ];

        // Merge the cacheability metadata of blocks into the page. This helps
        // to avoid cache redirects if the blocks have more cache contexts than
        // the page, which the page must respect as well.
        $cacheability
          ->addCacheableDependency($block);

        // If an alter hook wants to modify the block contents, it can append
        // another #pre_render hook.
        $this->moduleHandler
          ->alter([
          'block_view',
          'block_view_' . $block
            ->getBaseId(),
        ], $block_build, $block);
        $build[$region][$block_id] = $block_build;
      }
    }
    $build['#title'] = $this
      ->renderPageTitle($this->configuration['page_title']);
    $cacheability
      ->applyTo($build);
    return $build;
  }

  /**
   * #pre_render callback for building a block.
   *
   * Renders the content using the provided block plugin, if there is no
   * content, aborts rendering, and makes sure the block won't be rendered.
   */
  public function buildBlock($build) {
    $content = $build['#block_plugin']
      ->build();

    // Remove the block plugin from the render array.
    unset($build['#block_plugin']);
    if ($content !== NULL && !Element::isEmpty($content)) {
      $build['content'] = $content;
    }
    else {

      // Abort rendering: render as the empty string and ensure this block is
      // render cached, so we can avoid the work of having to repeatedly
      // determine whether the block is empty. E.g. modifying or adding entities
      // could cause the block to no longer be empty.
      $build = [
        '#markup' => '',
        '#cache' => $build['#cache'],
      ];
    }

    // If $content is not empty, then it contains cacheability metadata, and
    // we must merge it with the existing cacheability metadata. This allows
    // blocks to be empty, yet still bubble cacheability metadata, to indicate
    // why they are empty.
    if (!empty($content)) {
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromRenderArray($content))
        ->applyTo($build);
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    // Don't call VariantBase::buildConfigurationForm() on purpose, because it
    // adds a 'Label' field that we don't actually want to use - we store the
    // label on the page variant entity.

    //$form = parent::buildConfigurationForm($form, $form_state);

    // Allow to configure the page title, even when adding a new display.
    // Default to the page label in that case.
    $form['page_title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Page title'),
      '#description' => $this
        ->t('Configure the page title that will be used for this display.'),
      '#default_value' => $this->configuration['page_title'] ?: '',
    ];
    $form['uuid'] = [
      '#type' => 'value',
      '#value' => $this->configuration['uuid'] ?: $this->uuidGenerator
        ->generate(),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    if ($form_state
      ->hasValue('page_title')) {
      $this->configuration['page_title'] = $form_state
        ->getValue('page_title');
    }
    if ($form_state
      ->hasValue('uuid')) {
      $this->configuration['uuid'] = $form_state
        ->getValue('uuid');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getWizardOperations($cached_values) {
    return [
      'content' => [
        'title' => $this
          ->t('Content'),
        'form' => VariantPluginContentForm::class,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'page_title' => '',
    ];
  }

  /**
   * Renders the page title and replaces tokens.
   *
   * @param string $page_title
   *   The page title that should be rendered.
   *
   * @return string
   *   The page title after replacing any tokens.
   */
  protected function renderPageTitle($page_title) {
    $data = $this
      ->getContextAsTokenData();

    // Token replace only escapes replacement values, ensure a consistent
    // behavior by also escaping the input and then returning it as a Markup
    // object to avoid double escaping.
    // @todo: Simplify this when core provides an API for this in
    //   https://www.drupal.org/node/2580723.
    $title = (string) $this->token
      ->replace(new HtmlEscapedText($page_title), $data);
    return Markup::create($title);
  }

  /**
   * Returns available context as token data.
   *
   * @return array
   *   An array with token data values keyed by token type.
   */
  protected function getContextAsTokenData() {
    $data = [];
    foreach ($this
      ->getContexts() as $context) {

      // @todo Simplify this when token and typed data types are unified in
      //   https://drupal.org/node/2163027.
      if (strpos($context
        ->getContextDefinition()
        ->getDataType(), 'entity:') === 0) {
        $token_type = substr($context
          ->getContextDefinition()
          ->getDataType(), 7);
        if ($token_type == 'taxonomy_term') {
          $token_type = 'term';
        }
        $data[$token_type] = $context
          ->getContextValue();
      }
    }
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getRegionNames() {
    return [
      'top' => 'Top',
      'bottom' => 'Bottom',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function __sleep() {
    $vars = parent::__sleep();

    // Gathered contexts objects should not be serialized.
    if (($key = array_search('contexts', $vars)) !== FALSE) {
      unset($vars[$key]);
    }
    return $vars;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxFormTrait::getAjaxAttributes public static function Gets attributes for use with an AJAX modal.
AjaxFormTrait::getAjaxButtonAttributes public static function Gets attributes for use with an add button AJAX modal.
BlockDisplayVariant::$account protected property The current user.
BlockDisplayVariant::$contextHandler protected property The context handler.
BlockDisplayVariant::$contexts protected property An array of collected contexts.
BlockDisplayVariant::$token protected property The token service.
BlockDisplayVariant::$uuidGenerator protected property The UUID generator.
BlockDisplayVariant::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides VariantBase::calculateDependencies
BlockDisplayVariant::contextHandler protected function
BlockDisplayVariant::getBlockConfig protected function Returns the configuration for stored blocks. Overrides BlockVariantTrait::getBlockConfig
BlockDisplayVariant::getConfiguration public function Gets this plugin's configuration. Overrides VariantBase::getConfiguration
BlockDisplayVariant::getContexts public function Gets the contexts. Overrides ContextAwareVariantInterface::getContexts
BlockDisplayVariant::setConfiguration public function Sets the configuration for this plugin instance. Overrides VariantBase::setConfiguration
BlockDisplayVariant::setContexts public function Sets the contexts. Overrides ContextAwareVariantInterface::setContexts
BlockDisplayVariant::uuidGenerator protected function Returns the UUID generator. Overrides BlockVariantTrait::uuidGenerator
BlockVariantTrait::$blockManager protected property The block manager.
BlockVariantTrait::$blockPluginCollection protected property The plugin collection that holds the block plugins.
BlockVariantTrait::$eventDispatcher protected property The event dispatcher.
BlockVariantTrait::addBlock public function
BlockVariantTrait::eventDispatcher protected function Gets the event dispatcher.
BlockVariantTrait::getBlock public function
BlockVariantTrait::getBlockCollection protected function Returns the block plugins used for this display variant.
BlockVariantTrait::getBlockManager protected function Gets the block plugin manager.
BlockVariantTrait::getRegionAssignment public function
BlockVariantTrait::getRegionAssignments public function
BlockVariantTrait::getRegionName public function
BlockVariantTrait::removeBlock public function
BlockVariantTrait::updateBlock public function
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::getCacheContexts public function 3
CacheableDependencyTrait::getCacheMaxAge public function 3
CacheableDependencyTrait::getCacheTags public function 3
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PageBlockDisplayVariant::$moduleHandler protected property The module handler.
PageBlockDisplayVariant::build public function Builds and returns the renderable array for the display variant. Overrides VariantInterface::build
PageBlockDisplayVariant::buildBlock public function #pre_render callback for building a block.
PageBlockDisplayVariant::buildConfigurationForm public function Form constructor. Overrides VariantBase::buildConfigurationForm
PageBlockDisplayVariant::buildRegions public function #pre_render callback for building the regions.
PageBlockDisplayVariant::create public static function Creates an instance of the plugin. Overrides BlockDisplayVariant::create
PageBlockDisplayVariant::defaultConfiguration public function Gets default configuration for this plugin. Overrides BlockDisplayVariant::defaultConfiguration
PageBlockDisplayVariant::getContextAsTokenData protected function Returns available context as token data.
PageBlockDisplayVariant::getRegionNames public function Overrides BlockVariantTrait::getRegionNames
PageBlockDisplayVariant::getWizardOperations public function Retrieve a list of FormInterface classes by their step key in the wizard. Overrides PluginWizardInterface::getWizardOperations
PageBlockDisplayVariant::renderPageTitle protected function Renders the page title and replaces tokens.
PageBlockDisplayVariant::submitConfigurationForm public function Form submission handler. Overrides VariantBase::submitConfigurationForm
PageBlockDisplayVariant::__construct public function Constructs a new BlockDisplayVariant. Overrides BlockDisplayVariant::__construct
PageBlockDisplayVariant::__sleep public function Overrides BlockDisplayVariant::__sleep
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
VariantBase::access public function Determines if this display variant is accessible. Overrides VariantInterface::access
VariantBase::adminLabel public function Returns the admin-facing display variant label. Overrides VariantInterface::adminLabel
VariantBase::getWeight public function Returns the weight of the display variant. Overrides VariantInterface::getWeight
VariantBase::id public function Returns the unique ID for the display variant. Overrides VariantInterface::id
VariantBase::label public function Returns the user-facing display variant label. Overrides VariantInterface::label
VariantBase::setWeight public function Sets the weight of the display variant. Overrides VariantInterface::setWeight
VariantBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm