You are here

PdbBlock.php in Decoupled Blocks 8

File

src/Plugin/Block/PdbBlock.php
View source
<?php

namespace Drupal\pdb\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\Plugin\DataType\EntityAdapter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\pdb\FrameworkAwareBlockInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class PdbBlock.
 *
 * @package Drupal\pdb\Plugin\Block
 */
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;
  }

}

Classes

Namesort descending Description
PdbBlock Class PdbBlock.