entity_value_inheritance-1.3.0/src/EntityValueInheritanceUpdaterPluginBase.php

src/EntityValueInheritanceUpdaterPluginBase.php
<?php

namespace Drupal\entity_value_inheritance;

use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\PluginWithFormsInterface;
use Drupal\Core\Plugin\PluginWithFormsTrait;
use Drupal\Core\Render\Element;
use Drupal\entity_value_inheritance\Entity\InheritanceInterface;
use Drupal\entity_value_inheritance\Event\InheritanceAlterFieldEvent;
use Drupal\entity_value_inheritance\Event\InheritanceEvents;
use Drupal\entity_value_inheritance\Services\Helper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Base class for EntityValueInheritanceUpdaterPluginBase Plugins.
 *
 * Plugins are the bases with how the data is controlled in terms of the
 * update process.
 */
abstract class EntityValueInheritanceUpdaterPluginBase extends PluginBase implements EntityValueInheritanceUpdaterPluginInterface, PluginWithFormsInterface, ContainerFactoryPluginInterface {

  use PluginWithFormsTrait;

  /**
   * Event Dispatcher Service.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected EventDispatcherInterface $eventDispatcher;

  /**
   * Inheritance Element.
   *
   * @var \Drupal\entity_value_inheritance\Entity\InheritanceInterface
   */
  protected ?InheritanceInterface $inheritance = NULL;

  /**
   * Helper Service.
   *
   * @var \Drupal\entity_value_inheritance\Services\Helper
   */
  protected Helper $helper;

  /**
   * Cache Service.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected CacheBackendInterface $cacheBackend;

  /**
   * Constructs a new \Drupal\entity_value_inheritance\EntityValueInheritanceUpdaterPluginBase object.
   *
   * @param array $configuration
   *   Configuration Details.
   * @param string $plugin_id
   *   ID of plugin being created.
   * @param mixed $plugin_definition
   *   Information about the plugin.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
   *   Event Dispatching Service.
   * @param \Drupal\entity_value_inheritance\Services\Helper $helper
   *   Helper Function Service.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cacheBackend
   *   Cache Backend Service.
   */
  public function __construct(array $configuration, string $plugin_id, mixed $plugin_definition, EventDispatcherInterface $eventDispatcher, Helper $helper, CacheBackendInterface $cacheBackend) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->eventDispatcher = $eventDispatcher;
    $this->helper = $helper;
    $this->setConfiguration($configuration);
    $this->cacheBackend = $cacheBackend;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    // @phpstan-ignore-next-line
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('event_dispatcher'),
      $container->get('entity_value_inheritance.helper'),
      $container->get('cache.default')
    );
  }

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

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

  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return [
      'id' => $this->getPluginId(),
      'provider' => $this->pluginDefinition['provider'],
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function setConfigurationValue($key, $value) {
    $this->configuration[$key] = $value;
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle(): string {
    return $this->pluginDefinition['title'];
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(): string {
    return $this->pluginDefinition['description'];
  }

  /**
   * {@inheritdoc}
   */
  public function getInheritance(): ?InheritanceInterface {
    return $this->inheritance;
  }

  /**
   * {@inheritdoc}
   */
  public function setInheritance(InheritanceInterface $inheritance): EntityValueInheritanceUpdaterPluginInterface {
    $this->inheritance = $inheritance;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function updateDestination(EntityInterface $sourceEntity, EntityInterface $destinationEntity): bool {
    try {
      $destinationEntity->set(
        $this->inheritance->get('destination_entity_field'),
        $sourceEntity->get($this->inheritance->get('source_entity_field'))->getValue()
      );
    }
    catch (\Exception $exception) {
      $this->helper->logger()->error($exception->getMessage());
      return FALSE;
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function alterForm(array $form, FormStateInterface $formState, EntityInterface $entity, FieldDefinitionInterface $fieldDefinition): array {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function alterFormField(array $element, FormStateInterface $formState, EntityInterface $entity, FieldDefinitionInterface $fieldDefinition): array {
    $message = '';

    /** @var \Drupal\entity_value_inheritance\Event\InheritanceAlterFieldEvent $event */
    $event = $this->eventDispatcher->dispatch(
      new InheritanceAlterFieldEvent($element, $message, $this->inheritance, $entity, $fieldDefinition, $formState),
      InheritanceEvents::ALTER_FIELD
    );

    $element = $event->getElement();
    $message = $event->getMessage();
    $this->addFieldMessage($element, $message);

    return $element;
  }

  /**
   * List of containers that are used for the field message.
   *
   * @return string[]
   *   Return a list of containers to top messaging
   */
  protected function getContainerList(): array {
    return ['fieldset', 'details'];
  }

  /**
   * Recursive function to loop through form elements.
   *
   * @param array $element
   *   Element to loop through.
   * @param string $message
   *   Message to apply to that field.
   */
  protected function addFieldMessage(array &$element, string $message = ''): void {
    // No need to continue if the message is empty.
    if (empty($message)) {
      return;
    }

    // If the #type attribute is set add description message.
    if (isset($element['#type'])) {
      $class = "inheritance-message inheritance-message--{$element['#type']}";
      $element['#description'] = ($element['#description'] ?? '') .
        "<span class=\"{$class}\">" .
        Xss::filter($message, ['i', 'em', 'b', 'strong']) .
        '</span>';
    }

    // Get a list of all containers to stop recursion on.
    $containerList = $this->getContainerList();
    if (isset($element['#type']) && in_array($element['#type'], $containerList)) {
      return;
    }

    $children = Element::getVisibleChildren($element);
    // If there are children then recurse the function.
    if (count($children) > 0) {
      foreach ($children as $child) {
        $this->addFieldMessage($element[$child], $message);
      }
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function inheritanceValidate(array $form, FormStateInterface $form_state): void {

  }

  /**
   * {@inheritdoc}
   */
  public function inheritanceSubmit(array $form, FormStateInterface $form_state): void {

  }

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

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $definition = $this->getPluginDefinition();
    $form['provider'] = [
      '#type' => 'value',
      '#value' => $definition['provider'],
    ];

    // Add plugin-specific settings for this inheritance updater type.
    $form += $this->inheritanceForm($form, $form_state);

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->inheritanceValidate($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state->getErrors()) {
      $this->configuration['provider'] = $form_state->getValue('provider');
      $this->inheritanceSubmit($form, $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function preSaveEntity(EntityInterface $entity): void {

  }

  /**
   * {@inheritdoc}
   */
  public function deleteEntity(EntityInterface $entity): void {

  }

  /**
   * {@inheritdoc}
   */
  public function entityLoad(EntityInterface $entity): void {

  }

  /**
   * {@inheritdoc}
   */
  public function entityLoadProperties(string $entity_type_id, array $entities = []): void {

  }

  /**
   * {@inheritdoc}
   */
  public function fieldGroupFormProcessAlter(array &$element, &$group, &$complete_form): void {

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc