external_entity-1.0.x-dev/src/Plugin/EntityReferenceSelection/ExternalEntitySelection.php

src/Plugin/EntityReferenceSelection/ExternalEntitySelection.php
<?php

declare(strict_types=1);

namespace Drupal\external_entity\Plugin\EntityReferenceSelection;

use Drupal\Core\Form\FormStateInterface;
use Drupal\external_entity\AjaxFormTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\external_entity\Contracts\ExternalEntityTypeInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;

/**
 * Define the external entity selection plugin.
 *
 * @EntityReferenceSelection(
 *   id = "default:external_entity",
 *   label = @Translation("External Entity"),
 *   group = "default",
 *   entity_types = {"external_entity"}
 * )
 */
class ExternalEntitySelection extends SelectionPluginBase implements ContainerFactoryPluginInterface {

  use AjaxFormTrait;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs for the external entity selection.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    EntityTypeManagerInterface $entity_type_manager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
  }

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

  /**
   * {@inheritDoc}
   */
  public function defaultConfiguration(): array {
    return [
      'type' => NULL,
      'resource' => NULL,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritDoc}
   */
  public function buildConfigurationForm(
    array $form,
    FormStateInterface $form_state,
  ): array {
    $form['#prefix'] = '<div id = "external-entity-selection">';
    $form['#suffix'] = '</div>';

    $type = $this->getFormStateValue(
      'type',
      $form_state,
      $this->getExternalEntityTypeId()
    );

    $form['type'] = [
      '#type' => 'select',
      '#title' => $this->t('Reference type'),
      '#options' => $this->externalEntityTypeOptions(),
      '#empty_option' => $this->t('- Select -'),
      '#default_value' => $type,
      '#required' => TRUE,
      '#depth' => 1,
      '#ajax' => [
        'event' => 'change',
        'method' => 'replaceWith',
        'callback' => [$this, 'ajaxFormDepthCallback'],
        'wrapper' => 'external-entity-selection',
      ],
    ];
    if (isset($type) && !empty($type)) {
      /** @var \Drupal\external_entity\Entity\ExternalEntityType $external_entity_type */
      $external_entity_type = $this->externalEntityTypeStorage()->load($type);
      $resource_options = $external_entity_type->getResourceOptions()['resources'] ?? [];

      $form['resource'] = [
        '#type' => 'select',
        '#title' => $this->t('Reference resource'),
        '#options' => $resource_options,
        '#empty_option' => $this->t('- Select -'),
        '#required' => TRUE,
        '#default_value' => $this->getExternalEntityResource(),
      ];
    }

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function getReferenceableEntities(
    $match = NULL,
    $match_operator = 'CONTAINS',
    $limit = 0,
  ): array {
    $entities = [];
    /** @var \Drupal\external_entity\Entity\ExternalEntityStorage $external_entity_storage */
    $external_entity_storage = $this->externalEntityStorage();
    $external_entity_type_id = $this->getExternalEntityTypeId();
    $query = $external_entity_storage->getResourceQuery(
      $this->getExternalEntityResource(),
      $external_entity_type_id
    );
    $query
      ->condition('label', $match, $match_operator)
      ->pager($limit);

    // $response = $query->execute();
    return $entities;
  }

  /**
   * {@inheritDoc}
   */
  public function countReferenceableEntities(
    $match = NULL,
    $match_operator = 'CONTAINS',
  ): int {
    return 1;
  }

  /**
   * {@inheritDoc}
   */
  public function validateReferenceableEntities(array $ids): array {
    // @todo check ids using the external entity storage api
    return $ids;
  }

  /**
   * @return string|null
   */
  protected function getExternalEntityTypeId(): ?string {
    return $this->getConfiguration()['type'];
  }

  /**
   * @return \Drupal\external_entity\Contracts\ExternalEntityTypeInterface
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getExternalEntityType(): ExternalEntityTypeInterface {
    return $this->externalEntityTypeStorage()->load($this->getExternalEntityTypeId());
  }

  /**
   * @return string|null
   */
  protected function getExternalEntityResource(): ?string {
    return $this->getConfiguration()['resource'];
  }

  /**
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function externalEntityTypeOptions(): array {
    $options = [];

    foreach ($this->externalEntityTypeStorage()->loadMultiple() as $id => $definition) {
      $options[$id] = $definition->label();
    }

    return $options;
  }

  /**
   * Define the external entity storage.
   *
   * @return \Drupal\Core\Entity\EntityStorageInterface
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function externalEntityStorage(): EntityStorageInterface {
    return $this->entityTypeManager->getStorage('external_entity');
  }

  /**
   * Define the external entity type storage.
   *
   * @return \Drupal\Core\Entity\EntityStorageInterface
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function externalEntityTypeStorage(): EntityStorageInterface {
    return $this->entityTypeManager->getStorage('external_entity_type');
  }

}

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

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