You are here

BlockStyleBase.php in Block Style Plugins 8.2

Same filename and directory in other branches
  1. 8 src/Plugin/BlockStyleBase.php

File

src/Plugin/BlockStyleBase.php
View source
<?php

namespace Drupal\block_style_plugins\Plugin;

use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\PluginFormInterface;

/**
 * Base class for Block style plugins.
 */
abstract class BlockStyleBase extends PluginBase implements BlockStyleInterface, ContainerFactoryPluginInterface, PluginFormInterface {

  /**
   * Plugin ID for the Block being configured.
   *
   * @var string
   */
  protected $pluginId;

  /**
   * Instance of the Entity Type Manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Construct method for BlockStyleBase.
   *
   * @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\Entity\EntityTypeManagerInterface $entityTypeManager
   *   An Entity Type Manager instance.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    // Store our dependencies.
    $this->entityTypeManager = $entityTypeManager;

    // Store the plugin ID.
    $this->pluginId = $plugin_id;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'));
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function build(array $variables) {

    // Is the Layout Builder being used for block components?
    $layout_builder_block = empty($variables['elements']['#id']) && empty($variables['layout']) ? TRUE : FALSE;
    $styles = $this
      ->getStylesFromVariables($variables);
    if (!$styles) {
      return $variables;
    }

    // Layout Builder needs a '#'.
    $hash = $layout_builder_block ? '#' : '';

    // Add styles to the configuration array so that they can be accessed in a
    // preprocess $variables['configuration']['block_styles'] or in a twig
    // template as {{ configuration.block_styles.plugin_id.field_name }}.
    $variables[$hash . 'configuration']['block_styles'][$this->pluginId] = $styles;

    // Automaticlly add each style value as a class.
    if (empty($this->pluginDefinition['disable_auto_classes'])) {
      foreach ($styles as $class) {

        // Don't put a boolean from a checkbox as a class.
        if (is_int($class)) {
          continue;
        }

        // Create the attributes class array if it doesn't exist yet.
        if (!isset($variables[$hash . 'attributes']['class'])) {
          $variables[$hash . 'attributes']['class'] = [];
        }

        // Add the class into an array unless it is already an array of classes.
        if (!is_array($class)) {
          $class = [
            $class,
          ];
        }

        // Add single or multiple classes.
        $variables[$hash . 'attributes']['class'] = array_merge($variables[$hash . 'attributes']['class'], $class);
      }
    }
    return $variables;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = NestedArray::mergeDeep($this
      ->defaultConfiguration(), $configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function themeSuggestion(array $suggestions, array $variables) {
    return $suggestions;
  }

  /**
   * Get styles for a block set in a preprocess $variables array.
   *
   * @param array $variables
   *   Block variables coming from a preprocess hook.
   *
   * @return array|false
   *   Return the styles array or FALSE
   */
  protected function getStylesFromVariables(array $variables) {
    $styles = FALSE;

    // Ensure that we have a block id. If not, then the Layout Builder is used.
    if (empty($variables['elements']['#id'])) {
      $styles = $this
        ->getConfiguration();

      // Style config might not be set if this is happening in a hook so we will
      // check if a block_styles variable is set and get the config.
      if (empty($styles) && isset($variables['elements']['#configuration']['block_styles'][$this->pluginId])) {
        $this
          ->setConfiguration($variables['elements']['#configuration']['block_styles'][$this->pluginId]);
        $styles = $this
          ->getConfiguration();
      }
    }
    else {

      // Load the block config entity.

      /** @var \Drupal\block\Entity\Block $block */
      $block = $this->entityTypeManager
        ->getStorage('block')
        ->load($variables['elements']['#id']);

      // In the case that this block is placed via Context, it's not a "real"
      // block so it will be null. Attempt to get the block via variables.
      if (empty($block) && !empty($variables['elements']['#block'])) {
        $block = $variables['elements']['#block'];
      }

      // Check that we loaded a block.
      if (!empty($block)) {
        $styles = $block
          ->getThirdPartySetting('block_style_plugins', $this->pluginId);
        if ($styles) {
          $this
            ->setConfiguration($styles);
        }
      }
    }
    return $styles;
  }

}

Classes

Namesort descending Description
BlockStyleBase Base class for Block style plugins.