You are here

abstract class PatternSettingTypeBase in UI Patterns Settings 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/PatternSettingTypeBase.php \Drupal\ui_patterns_settings\Plugin\PatternSettingTypeBase

Base class for UI Patterns Setting plugins.

Hierarchy

Expanded class hierarchy of PatternSettingTypeBase

8 files declare their use of PatternSettingTypeBase
AttributesSettingType.php in src/Plugin/UiPatterns/SettingType/AttributesSettingType.php
BooleanSettingType.php in src/Plugin/UiPatterns/SettingType/BooleanSettingType.php
CheckboxesSettingType.php in src/Plugin/UiPatterns/SettingType/CheckboxesSettingType.php
GroupType.php in src/Plugin/UiPatterns/SettingType/GroupType.php
MediaLibrarySettingType.php in src/Plugin/UiPatterns/SettingType/MediaLibrarySettingType.php

... See full list

File

src/Plugin/PatternSettingTypeBase.php, line 19

Namespace

Drupal\ui_patterns_settings\Plugin
View source
abstract class PatternSettingTypeBase extends PluginBase implements ConfigurableInterface, PatternSettingTypeInterface, ContainerFactoryPluginInterface {

  /**
   * Returns a list of plugin dependencies.
   *
   * @return bool
   *   True if all dependencies exist.
   */
  protected function getSettingTypeDependencies() {
    return [];
  }

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

  /**
   * Return pattern definitions for setting .
   *
   * @var \Drupal\ui_patterns\Definition\PatternDefinition
   */
  private $patternDefinition;

  /**
   * Return pattern definitions for setting .
   *
   * @var \Drupal\ui_patterns_settings\Definition\PatternDefinitionSetting
   */
  private $patternSettingDefinition;

  /**
   * Return pattern definitions for setting .
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager) {
    $configuration += $this
      ->defaultConfiguration();
    $this->patternSettingDefinition = $configuration['pattern_setting_definition'];
    $this->patternDefinition = $configuration['pattern_definition'];
    $this->moduleHandler = $module_handler;
    $this->entityTypeManager = $entity_type_manager;
    unset($configuration['pattern_setting_definition']);
    unset($configuration['pattern_definition']);
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * Return value if set otherwise take the default value.
   *
   * @param mixed $value
   *   The provided value.
   *
   * @return string
   *   The value for this setting
   */
  protected function getValue($value) {
    if ($value === NULL) {
      return $this
        ->getPatternSettingDefinition()
        ->getDefaultValue();
    }
    else {
      return $value === NULL ? "" : $value;
    }
  }

  /**
   * Return pattern setting definition.
   *
   * @return \Drupal\ui_patterns_settings\Definition\PatternDefinitionSetting
   *   Pattern setting definition.
   */
  protected function getPatternSettingDefinition() {
    return $this->patternSettingDefinition;
  }

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

    /** @var \Drupal\Core\StringTranslation\TranslationInterface $translation */
    $translation = $container
      ->get('string_translation');
    $plugin
      ->setStringTranslation($translation);
    return $plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function alterFieldStorage(FieldStorageConfig $storage_config) {
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    $plugin_definition = $this
      ->getPluginDefinition();
    return $plugin_definition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    $plugin_definition = $this
      ->getPluginDefinition();
    return isset($plugin_definition['description']) ? $plugin_definition['description'] : '';
  }

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

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

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

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

  /**
   * {@inheritdoc}
   */
  public function preprocess($value, array $context) {
    $def = $this
      ->getPatternSettingDefinition();
    $value = $this
      ->settingsPreprocess($value, $context, $def);
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsPreprocess($value, array $context, PatternDefinitionSetting $def) {
    return $value;
  }

  /**
   * Returns the bind form field.
   *
   * @param array $form
   *   The form definition array for the settings configuration form.
   * @param string $value
   *   The stored default value.
   * @param \Drupal\ui_patterns_settings\Definition\PatternDefinitionSetting $def
   *   The pattern definition.
   *
   * @return array
   *   The form.
   */
  protected function tokenForm(array $form, $value, PatternDefinitionSetting $def) {
    $form[$def
      ->getName() . "_token"] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Token for %label", [
        '%label' => $def
          ->getLabel(),
      ]),
      '#default_value' => $this
        ->getValue($value),
      '#attributes' => [
        'class' => [
          'js-ui-patterns-settings-show-token-link',
          'js-ui-patterns-settings__token',
        ],
      ],
      '#wrapper_attributes' => [
        'class' => [
          'js-ui-patterns-settings__token-wrapper',
        ],
      ],
    ];
    return $form;
  }

  /**
   * Check required input fields in layout forms.
   *
   * @param array $element
   *   The element to validate.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param array $form
   *   The form.
   */
  public static function validateLayout(array $element, FormStateInterface &$form_state, array &$form) {
    $parents = $element['#parents'];
    $value = $form_state
      ->getValue($parents);
    $parents[count($parents) - 1] = $parents[count($parents) - 1] . '_token';
    $token_value = $form_state
      ->getValue($parents);
    if (empty($value) && empty($token_value)) {

      // Check if a variant is selected and the value
      // is provided by the variant.
      $variant = $form_state
        ->getValue([
        'layout_configuration',
        'pattern',
        'variant',
      ]);
      if (!empty($variant)) {
        $variant_def = $element['#pattern_definition']
          ->getVariant($variant);
        $variant_ary = $variant_def
          ->toArray();
        if (!empty($variant_ary['settings'][$element['#pattern_setting_definition']
          ->getName()])) {
          return;
        }
      }
      $form_state
        ->setError($element, t('@name field is required.', [
        '@name' => $element['#title'],
      ]));
    }
  }

  /**
   * Add validation and basics classes to the raw input field.
   *
   * @param array $input
   *   The input field.
   * @param \Drupal\ui_patterns_settings\Definition\PatternDefinitionSetting $def
   *   The pattern definition.
   * @param string $form_type
   *   The form type. Either layouts_display or display.
   */
  protected function handleInput(array &$input, PatternDefinitionSetting $def, $form_type) {
    $input['#attributes']['class'][] = 'js-ui-patterns-settings__input';
    $input['#wrapper_attributes']['class'][] = 'js-ui-patterns-settings__input-wrapper';
    if ($def
      ->getRequired()) {
      $input['#title'] .= ' *';
      if ($form_type === 'layouts_display') {
        $input['#element_validate'][] = [
          PatternSettingTypeBase::class,
          'validateLayout',
        ];
      }
    }
  }

  /**
   * {@inheritdoc}
   *
   * Creates a generic configuration form for all settings types.
   * Individual settings plugins can add elements to this form by
   * overriding PatternSettingTypeBaseInterface::settingsForm().
   * Most plugins should not override this method unless they
   * need to alter the generic form elements.
   *
   * @see \Drupal\Core\Block\BlockBase::blockForm()
   */
  public function buildConfigurationForm(array $form, $value, $token_value, $form_type) {
    $dependencies = $this
      ->getSettingTypeDependencies();
    $def = $this
      ->getPatternSettingDefinition();
    foreach ($dependencies as $dependency) {
      if (!$this->moduleHandler
        ->moduleExists($dependency)) {
        $form[$def
          ->getName()] = [
          '#markup' => "Missing SettingType {$def->getName()} dependency {$dependency}.",
        ];
        return $form;
      }
    }
    $form = $this
      ->settingsForm($form, $value, $def, $form_type);
    $form[$def
      ->getName()]['#pattern_setting_definition'] = $def;
    $form[$def
      ->getName()]['#pattern_definition'] = $this->patternDefinition;
    if (!empty($def
      ->getWeight())) {
      $form[$def
        ->getName()]['#weight'] = $def
        ->getWeight();
    }
    if ($def
      ->getAllowToken()) {
      $form = $this
        ->tokenForm($form, $token_value, $def);
      if (isset($form[$def
        ->getName() . '_token'])) {
        $classes = 'js-ui-patterns-settings__wrapper';
        if (!empty($token_value)) {
          $classes .= ' js-ui-patterns-settings--token-has-value';
        }
        $form[$def
          ->getName()]['#prefix'] = '<div class="' . $classes . '">';
        $form[$def
          ->getName() . '_token']['#suffix'] = '</div>';
        $form[$def
          ->getName() . '_token']['#pattern_setting_definition'] = $def;
        $form[$def
          ->getName() . '_token']['#pattern_definition'] = $this->patternDefinition;
      }
    }
    return $form;
  }

  /**
   * Set the right group before drupal #group attribute is processed.
   *
   * @param array $element
   *   The form field.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The pattern definition.
   * @param mixed $form
   *   The form.
   *
   * @return array
   *   The processed element.
   */
  public static function formGroupProcess(array &$element, FormStateInterface $form_state = NULL, &$form = []) {
    if (isset($element['#pattern_setting_definition'])) {
      $setting_definition = $element['#pattern_setting_definition'];
      if ($setting_definition
        ->getGroup() !== NULL) {
        $parents = $element['#parents'];
        array_pop($parents);
        $parents[] = $setting_definition
          ->getGroup();
        $element['#group'] = implode('][', $parents);
      }
    }
    return $element;
  }

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

  /**
   * {@inheritdoc}
   */
  public function preprocessExposedField(FieldItemList $items) {
    foreach ($items as $item) {
      return $item->value;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
PatternSettingTypeBase::$entityTypeManager protected property Return pattern definitions for setting .
PatternSettingTypeBase::$moduleHandler private property The module handler.
PatternSettingTypeBase::$patternDefinition private property Return pattern definitions for setting .
PatternSettingTypeBase::$patternSettingDefinition private property Return pattern definitions for setting .
PatternSettingTypeBase::alterFieldStorage public function Alter the storage of a connected field storage. Overrides PatternSettingTypeInterface::alterFieldStorage 1
PatternSettingTypeBase::buildConfigurationForm public function Creates a generic configuration form for all settings types. Individual settings plugins can add elements to this form by overriding PatternSettingTypeBaseInterface::settingsForm(). Most plugins should not override this method unless they need to… Overrides PatternSettingTypeInterface::buildConfigurationForm
PatternSettingTypeBase::calculateDependencies public function
PatternSettingTypeBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
PatternSettingTypeBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
PatternSettingTypeBase::fieldStorageExposableTypes public function Returns the list to matching field types. Overrides PatternSettingTypeInterface::fieldStorageExposableTypes 2
PatternSettingTypeBase::formGroupProcess public static function Set the right group before drupal #group attribute is processed.
PatternSettingTypeBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
PatternSettingTypeBase::getDescription public function
PatternSettingTypeBase::getPatternSettingDefinition protected function Return pattern setting definition.
PatternSettingTypeBase::getSettingTypeDependencies protected function Returns a list of plugin dependencies. 2
PatternSettingTypeBase::getValue protected function Return value if set otherwise take the default value. 1
PatternSettingTypeBase::handleInput protected function Add validation and basics classes to the raw input field. 1
PatternSettingTypeBase::label public function
PatternSettingTypeBase::preprocess public function Returns the processed setting variable. Overrides PatternSettingTypeInterface::preprocess 1
PatternSettingTypeBase::preprocessExposedField public function Returns the processed setting variable for an exposed field. Overrides PatternSettingTypeInterface::preprocessExposedField 1
PatternSettingTypeBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
PatternSettingTypeBase::settingsPreprocess public function Preprocess setting variable. Overrides PatternSettingTypeInterface::settingsPreprocess 5
PatternSettingTypeBase::tokenForm protected function Returns the bind form field.
PatternSettingTypeBase::validateLayout public static function Check required input fields in layout forms.
PatternSettingTypeBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
PatternSettingTypeInterface::settingsForm public function Returns the configuration form elements specific to this settings plugin.. 9
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.
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.