You are here

abstract class PdbBlock in Decoupled Blocks 8

Class PdbBlock.

@package Drupal\pdb\Plugin\Block

Hierarchy

Expanded class hierarchy of PdbBlock

4 files declare their use of PdbBlock
EmberBlock.php in modules/pdb_ember/src/Plugin/Block/EmberBlock.php
Ng2Block.php in modules/pdb_ng2/src/Plugin/Block/Ng2Block.php
PdbBlockTest.php in tests/src/Unit/Plugin/Block/PdbBlockTest.php
ReactBlock.php in modules/pdb_react/src/Plugin/Block/ReactBlock.php

File

src/Plugin/Block/PdbBlock.php, line 17

Namespace

Drupal\pdb\Plugin\Block
View source
abstract class PdbBlock extends BlockBase implements FrameworkAwareBlockInterface, ContainerFactoryPluginInterface {

  /**
   * PdbBlock constructor.
   *
   * @param array $configuration
   *   Plugin configuration.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin definition.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $component = $this
      ->getComponentInfo();
    $this->configuration['uuid'] = \Drupal::service('uuid')
      ->generate();
    $attached = [];
    $framework = $this
      ->attachFramework($component);
    if ($framework) {
      $attached = array_merge_recursive($attached, $framework);
    }
    $settings = $this
      ->attachSettings($component);
    if ($settings) {
      $attached = array_merge_recursive($attached, $settings);
    }
    $libraries = $this
      ->attachLibraries($component);
    if ($libraries) {
      $attached = array_merge_recursive($attached, $libraries);
    }
    $header = $this
      ->attachPageHeader($component);
    if ($header) {
      $attached = array_merge_recursive($attached, $header);
    }
    $contexts = $this
      ->getContexts();
    if ($contexts) {
      $contexts_values = $this
        ->getContextsValues($contexts);
      $this->configuration['contexts'] = $contexts_values;
      $js_contexts = $this
        ->getJsContexts($contexts_values);
      $attached['drupalSettings']['pdb']['contexts'] = $js_contexts;
    }
    if (isset($this->configuration['pdb_configuration'])) {

      // @todo Is there anything else unique to key off of besides uuid
      $attached['drupalSettings']['pdb']['configuration'][$this->configuration['uuid']] = $this->configuration['pdb_configuration'];
    }
    return [
      '#attached' => $attached,
    ];
  }

  /**
   * Returns the component definition.
   *
   * @return array
   *   The component definition.
   */
  public function getComponentInfo() {
    $plugin_definition = $this
      ->getPluginDefinition();
    return $plugin_definition['info'];
  }

  /**
   * {@inheritdoc}
   */
  public function attachFramework(array $component) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function attachLibraries(array $component) {

    // Attach the header and footer component library.
    $path = 'pdb/' . $component['machine_name'];
    $component_libraries = [];
    if (isset($component['add_css']['header']) || isset($component['add_js']['header'])) {
      $component_libraries[] = $path . '/header';
    }
    if (isset($component['add_css']['footer']) || isset($component['add_js']['footer'])) {
      $component_libraries[] = $path . '/footer';
    }
    return $component_libraries;
  }

  /**
   * {@inheritdoc}
   */
  public function attachSettings(array $component) {
    if (isset($component['settings'])) {
      return [
        'drupalSettings' => $component['settings'],
      ];
    }
    else {
      return [];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function attachPageHeader(array $component) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['pdb_configuration'] = $this
      ->buildComponentSettingsForm($form_state);
    return $form;
  }

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

  /**
   * Get the value of contexts.
   *
   * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
   *   The contexts to get value.
   *
   * @return array
   *   An array of contexts values.
   */
  protected function getContextsValues(array $contexts) {
    $context_values = [];
    foreach ($contexts as $key => $context) {
      $data = $context
        ->getContextData();
      if ($data instanceof EntityAdapter) {
        $this
          ->getContextEntityValue($key, $data, $context_values);
      }
      else {

        // Get the data value otherwise.
        $context_values[$key] = $data
          ->getValue();
      }
    }
    return $context_values;
  }

  /**
   * Get context value for Entity context.
   *
   * @param string $key
   *   The context key.
   * @param \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $data
   *   The context data.
   * @param array $context_values
   *   Array with contexts values.
   */
  protected function getContextEntityValue($key, EntityAdapter $data, array &$context_values) {
    $entity_context = $data
      ->getValue();
    if (!isset($context_values["{$key}:" . $entity_context
      ->getEntityTypeId()])) {

      // Get a copy of the context entity so we do not alter the original one.
      $entity = clone $entity_context;
      $entity_access = $entity
        ->access('view', NULL, TRUE);
      if (!$entity_access
        ->isAllowed()) {
        return;
      }
      foreach ($entity as $field_name => $field) {

        // @var \Drupal\Core\Field\FieldItemListInterface $field
        $field_access = $field
          ->access('view', NULL, TRUE);

        // @todo Used addCacheableDependency($field_access);
        if (!$field_access
          ->isAllowed()) {
          $entity
            ->set($field_name, NULL);
        }
      }
      $context_values["{$key}:" . $entity
        ->getEntityTypeId()] = $entity;
    }
  }

  /**
   * Add serialized entity to the JS Contexts.
   *
   * @param \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $data
   *   The entity to serialize.
   * @param array $js_contexts
   *   The full array of JS contexts.
   * @param string $key
   *   The context key.
   *
   * @deprecated in pdb:8.x-1.0 and is removed from pdb:2.0.0.
   *   Instead, you should just use ::getContextEntityValue().
   */
  protected function addEntityJsContext(EntityAdapter $data, array &$js_contexts, $key) {
    @trigger_error('addEntityJsContext() is deprecated in pdb:8.x-1.0 and is removed from pdb:2.0.0. Use ::getContextEntityValue() instead.', E_USER_DEPRECATED);
    $this
      ->getContextEntityValue($key, $data, $js_contexts);
  }

  /**
   * Get an array of serialized JS contexts.
   *
   * @param array $contexts
   *   The contexts to serialize.
   *
   * @return array
   *   An array of serialized JS contexts.
   */
  protected function getJsContexts(array $contexts) {
    $js_contexts = [];
    foreach ($contexts as $key => $context) {
      if (is_object($context) && method_exists($context, 'toArray')) {

        // Get the array version of the entity context.
        $js_contexts[$key] = $context
          ->toArray();
      }
      else {

        // Leave the context as it is otherwise.
        $js_contexts[$key] = $context;
      }
    }
    return $js_contexts;
  }

  /**
   * Build settings component settings form.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state array.
   */
  protected function buildComponentSettingsForm(FormStateInterface $form_state) {
    $definition = $this
      ->getPluginDefinition();
    $elements = [];
    if (isset($definition['info']['configuration'])) {
      $elements = $this
        ->createElementsFromConfiguration($definition['info']['configuration'], $form_state);
      $elements['#title'] = $this
        ->t('Component Settings');
      $elements['#type'] = 'details';
      $elements['#open'] = TRUE;
      $elements['#tree'] = TRUE;
    }
    return $elements;
  }

  /**
   * Create Form API elements from component configuration.
   *
   * @param array $configuration
   *   The configuration array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state array.
   *
   * @return array
   *   Form elements.
   */
  protected function createElementsFromConfiguration($configuration, FormStateInterface $form_state) {
    $elements = [];
    $defaults = !empty($this->configuration['pdb_configuration']) ? $this->configuration['pdb_configuration'] : [];
    foreach ($configuration as $key => $setting) {
      $element = [];
      foreach ($setting as $property_key => $property) {

        // @todo Create whitelist or blacklist of form api properties
        $element["#{$property_key}"] = $property;
      }
      if (isset($defaults[$key])) {
        $element['#default_value'] = $this
          ->getElementDefaultValue($defaults[$key]);
      }
      $elements[$key] = $element;
    }
    return $elements;
  }

  /**
   * Gets the actual default field value of a given field element defaults.
   *
   * @param mixed $element_defaults
   *   The element default values.
   *
   * @return mixed
   *   The actual element default value.
   */
  protected function getElementDefaultValue($element_defaults) {

    // @todo are there any other ways to get the actual default value?
    // Some form elements like "text_format" store the default values as an
    // array and the actual default value is stored on the "value" key.
    if (is_array($element_defaults) && isset($element_defaults['value'])) {
      return $element_defaults['value'];
    }
    return $element_defaults;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockForm public function 16
BlockPluginTrait::blockSubmit public function 13
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::defaultConfiguration public function 19
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
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::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PdbBlock::addEntityJsContext Deprecated protected function Add serialized entity to the JS Contexts.
PdbBlock::attachFramework public function Attaches the framework required by the component. Overrides FrameworkAwareBlockInterface::attachFramework 2
PdbBlock::attachLibraries public function Attaches any libraries required by the component. Overrides FrameworkAwareBlockInterface::attachLibraries 3
PdbBlock::attachPageHeader public function Attaches anything the component needs in the HTML <head>. Overrides FrameworkAwareBlockInterface::attachPageHeader
PdbBlock::attachSettings public function Attaches JavaScript settings required by the component. Overrides FrameworkAwareBlockInterface::attachSettings 3
PdbBlock::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build 3
PdbBlock::buildComponentSettingsForm protected function Build settings component settings form.
PdbBlock::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. Overrides BlockPluginTrait::buildConfigurationForm
PdbBlock::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
PdbBlock::createElementsFromConfiguration protected function Create Form API elements from component configuration.
PdbBlock::getComponentInfo public function Returns the component definition.
PdbBlock::getContextEntityValue protected function Get context value for Entity context.
PdbBlock::getContextsValues protected function Get the value of contexts.
PdbBlock::getElementDefaultValue protected function Gets the actual default field value of a given field element defaults.
PdbBlock::getJsContexts protected function Get an array of serialized JS contexts.
PdbBlock::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit(). Overrides BlockPluginTrait::submitConfigurationForm
PdbBlock::__construct public function PdbBlock constructor. Overrides BlockPluginTrait::__construct
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.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass 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.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2