Commit 128bae27 authored by Matt Glaman's avatar Matt Glaman Committed by Matt Glaman
Browse files

Issue #2763001 by mglaman: Integrate with plugins

parent 6ec7ca17
Loading
Loading
Loading
Loading
+33
Changes for commerce.module: 33 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -203,3 +203,36 @@ function commerce_module_preuninstall($module) {
    \Drupal::service('commerce.bundle_plugin_installer')->uninstallBundles($entity_type, [$module]);
  }
}

/**
 * Implements hook_action_info_alter().
 *
 * @todo: Core uses CategorizingPluginManagerTrait but does not implement.
 */
function commerce_action_info_alter(array &$definitions) {
  foreach ($definitions as &$definition) {
    // Ensure that every plugin has a category.
    if (empty($definition['category'])) {
      // Default to the human readable module name if the provider is a module;
      // otherwise the provider machine name is used.
      $definition['category'] = \Drupal::moduleHandler()->getName($definition['provider']);
    }
  }
}

/**
 * Implements hook_condition_info_alter().
 *
 * @todo: Core uses CategorizingPluginManagerTrait but does not implement.
 */
function commerce_condition_info_alter(array &$definitions) {
  foreach ($definitions as &$definition) {
    // Ensure that every plugin has a category.
    if (empty($definition['category'])) {
      // Default to the human readable module name if the provider is a module;
      // otherwise the provider machine name is used.
      $definition['category'] = \Drupal::moduleHandler()
        ->getName($definition['provider']);
    }
  }
}
+10
Changes for config/schema/commerce.schema.yml: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -12,6 +12,16 @@ field.widget.settings.commerce_entity_select:
      type: string
      label: 'Autocomplete placeholder'

field.field_settings.commerce_plugin_item:*:
  type: mapping
  label: 'Plugin item field settings'
  mapping:
    categories:
      type: sequence
      label: 'Categories'
      sequence:
        - type: string

views.argument_validator.commerce_current_user:
  type: mapping
  label: 'Current user'
+176
Changes for src/Element/PluginSelect.php: 176 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace Drupal\commerce\Element;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Render\Element\FormElement;
use Symfony\Component\HttpFoundation\Request;

/**
 * Element for selecting plugins, and configuring them.
 *
 * @FormElement("commerce_plugin_select")
 *
 * Properties:
 * - #providers: Modules to restrict options to.
 *
 * Usage example:
 * @code
 * $form['plugin_item'] = [
 *   '#type' => 'commerce_plugin_select',
 *   '#title' => $this->t('Condition plugin'),
 *   '#categories' => ['user', 'system'],
 * ];
 * @endcode
 */
class PluginSelect extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#plugin_type' => NULL,
      '#categories' => [],
      '#title' => $this->t('Select plugin'),
      '#process' => [
        [$class, 'processPluginSelect'],
        [$class, 'processAjaxForm'],
      ],
      '#element_validate' => [
        [$class, 'validatePlugin'],
      ],
    ];
  }

  /**
   * Process callback.
   */
  public static function processPluginSelect(&$element, FormStateInterface $form_state, &$complete_form) {
    if (!$element['#plugin_type']) {
      throw new \InvalidArgumentException('You must specify the plugin type ID.');
    }

    $element['#tree'] = TRUE;

    /** @var \Drupal\Core\Executable\ExecutableManagerInterface $plugin_manager */
    $plugin_manager = \Drupal::service('plugin.manager.' . $element['#plugin_type']);

    $values = $element['#value'];

    $target_plugin_id = !empty($values['target_plugin_id']) ? $values['target_plugin_id'] : '_none';

    $ajax_wrapper_id = Html::getUniqueId('ajax-wrapper');
    $ajax_settings = [
      'callback' => [get_called_class(), 'pluginFormAjax'],
      'wrapper' => $ajax_wrapper_id,
    ];

    // Prefix and suffix used for Ajax replacement.
    $element['#prefix'] = '<div id="' . $ajax_wrapper_id . '">';
    $element['#suffix'] = '</div>';

    // Store #array_parents in the form state, so we can get the elements from
    // the complete form array by using only thes form state.
    $element['array_parents'] = [
      '#type' => 'value',
      '#value' => $element['#array_parents'],
    ];

    $element['target_plugin_type'] = [
      '#type' => 'value',
      '#value' => $element['#plugin_type'],
    ];

    $element['target_plugin_id'] = [
      '#type' => 'select',
      '#title' => $element['#title'],
      '#multiple' => FALSE,
      '#options' => [
        '_none' => t('None'),
      ],
      '#ajax' => $ajax_settings,
      '#default_value' => $target_plugin_id,
      '#ajax_array_parents' => $element['#array_parents'],
    ];

    $categories = array_combine($element['#categories'], $element['#categories']);
    $has_categories = !empty($categories);
    foreach ($plugin_manager->getDefinitions() as $definition) {
      // If categories have been specified, limit definitions based on them.
      if ($has_categories && !isset($categories[$definition['category']])) {
        continue;
      }

      $element['target_plugin_id']['#options'][$definition['id']] = $definition['label'];
    }

    if ($target_plugin_id != '_none') {
      /** @var \Drupal\Core\Executable\ExecutableInterface $plugin */
      $plugin = $plugin_manager->createInstance($target_plugin_id, $values['target_plugin_configuration']);
      if ($plugin instanceof  PluginFormInterface) {
        $element['target_plugin_configuration'] = [
          '#tree' => TRUE,
        ];
        $element['target_plugin_configuration'] = $plugin->buildConfigurationForm($element['target_plugin_configuration'], $form_state);
      }
    }

    return $element;
  }

  /**
   * Ajax callback.
   */
  public static function pluginFormAjax(&$form, FormStateInterface &$form_state, Request $request) {
    // Retrieve the element to be rendered.
    $triggering_element = $form_state->getTriggeringElement();
    $form_element = NestedArray::getValue($form, $triggering_element['#ajax_array_parents']);
    return $form_element;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if (empty($input)) {
      $input = $element['#default_value'];
    }
    return $input + [
      'target_plugin_id' => NULL,
      'target_plugin_configuration' => [],
    ];
  }

  /**
   * Validates the plugin's configuration.
   *
   * @param array $element
   *   An associative array containing the properties of the element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   */
  public static function validatePlugin(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($element['#parents']);

    $target_plugin_id = $values['target_plugin_id'];

    // If a plugin was selected, create an instance and pass the configuration
    // values to its configuration form validation method.
    if ($target_plugin_id != '_none') {
      $plugin_manager = \Drupal::service('plugin.manager.' . $values['target_plugin_type']);
      $plugin = $plugin_manager->createInstance($target_plugin_id, $values['target_plugin_configuration']);
      if ($plugin instanceof  PluginFormInterface) {
        $plugin->validateConfigurationForm($element, $form_state);
      }
    }
  }

}
+134
Changes for src/Plugin/Field/FieldType/PluginItem.php: 134 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace Drupal\commerce\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\MapDataDefinition;

/**
 * Plugin implementation of the 'commerce_plugin_item' field type.
 *
 * @FieldType(
 *   id = "commerce_plugin_item",
 *   label = @Translation("Plugin"),
 *   description = @Translation("Stores configuration for a plugin."),
 *   default_widget = "commerce_plugin_select",
 *   default_formatter = "string",
 *   deriver = "\Drupal\commerce\Plugin\Field\FieldType\PluginItemDeriver"
 * )
 */
class PluginItem extends FieldItemBase implements PluginItemInterface {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['target_plugin_id'] = DataDefinition::create('string')
      ->setLabel(t('Plugin ID'));
    $properties['target_plugin_configuration'] = MapDataDefinition::create()
      ->setLabel(t('Plugin configuration'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'target_plugin_id' => [
          'description' => 'The plugin ID.',
          'type' => 'varchar_ascii',
          'length' => 255,
          'not null' => TRUE,
        ],
        'target_plugin_configuration' => [
          'description' => 'The plugin configuration.',
          'type' => 'blob',
          'not null' => TRUE,
          'serialize' => TRUE,
        ],
      ],
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $element = [];
    $element['categories'] = [
      '#type' => 'select',
      '#title' => $this->t('Plugin categories'),
      '#default_value' => $this->getSetting('categories'),
      '#multiple' => TRUE,
      '#size' => 5,
    ];

    $categories = [];
    foreach ($this->getPluginManager()->getDefinitions() as $definition) {
      if (!isset($definition['category'])) {
        continue;
      }
      $categories[$definition['category']] = $definition['category'];
    }

    $element['categories']['#options'] = $categories;

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return 'target_plugin_id';
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return empty($this->target_plugin_id) || $this->target_plugin_id == '_none';
  }

  /**
   * Gets the exectuable plugin's manager.
   *
   * @return \Drupal\Core\Executable\ExecutableManagerInterface|\Drupal\Component\Plugin\CategorizingPluginManagerInterface
   *   The plugin manager.
   */
  public function getPluginManager() {
    return \Drupal::service('plugin.manager.' . $this->getPluginDefinition()['plugin_type']);
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetInstance(array $contexts = []) {
    $plugin = $this->getPluginManager()
      ->createInstance($this->target_plugin_id, $this->target_plugin_configuration);

    // Just because the plugin is context aware, we cannot guarantee the
    // plugin manager sets them. So we apply the context mapping as well.
    if (!empty($contexts)) {
      \Drupal::service('context.handler')->applyContextMapping($plugin, $contexts);
    }

    return $plugin;
  }

}
+34
Changes for src/Plugin/Field/FieldType/PluginItemDeriver.php: 34 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace Drupal\commerce\Plugin\Field\FieldType;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Deriver for the executable plugin item field type.
 */
class PluginItemDeriver extends DeriverBase {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $supported = [
      'condition' => $this->t('Conditions'),
      'action' => $this->t('Action'),
    ];

    foreach ($supported as $id => $label) {
      $this->derivatives[$id] = [
        'plugin_type' => $id,
        'label' => $label,
        'category' => $this->t('Plugin'),
      ] + $base_plugin_definition;
    }

    return parent::getDerivativeDefinitions($base_plugin_definition);
  }

}
Loading