external_entity-1.0.x-dev/src/Plugin/Field/FieldFormatter/ExternalEntityReferenceEntityFormatter.php

src/Plugin/Field/FieldFormatter/ExternalEntityReferenceEntityFormatter.php
<?php

declare(strict_types=1);

namespace Drupal\external_entity\Plugin\Field\FieldFormatter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\external_entity\Contracts\ExternalEntityTypeInterface;
use Drupal\external_entity\Contracts\ExternalEntityRenderTypeInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;

/**
 * Plugin implementation of the 'entity reference rendered entity' formatter.
 *
 * @FieldFormatter(
 *   id = "external_entity_reference_entity_view",
 *   label = @Translation("Rendered entity"),
 *   description = @Translation("Display the referenced external entities."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class ExternalEntityReferenceEntityFormatter extends EntityReferenceFormatterBase {

  /**
   * The number of times this formatter allows rendering the same entity.
   *
   * @var int
   */
  protected const RECURSIVE_RENDER_LIMIT = 20;

  /**
   * The logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

  /**
   * @var array
   *
   * An array of counters for the recursive rendering protection.
   *
   * Each counter takes into account all the relevant information about the
   * field and the referenced entity that is being rendered.
   *
   * @see \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter::viewElements()
   */
  protected static $recursiveRenderDepth = [];

  /**
   * Constructs a EntityReferenceEntityFormatter instance.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   The logger factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The entity display repository.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, LoggerChannelFactoryInterface $logger_factory, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->loggerFactory = $logger_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityDisplayRepository = $entity_display_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('logger.factory'),
      $container->get('entity_type.manager'),
      $container->get('entity_display.repository')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function settingsForm(
    array $form,
    FormStateInterface $form_state,
  ): array {
    $elements['variations'] = [
      '#type' => 'details',
      '#title' => $this->t('Variations'),
      '#open' => TRUE,
    ];
    $variations = $this->getSetting('variations');

    foreach ($this->getExternalEntityResourceVariations() as $variation => $info) {
      $options = $this->getResourceDisplayViewModeOptions($variation);
      $elements['variations'][$variation] = [
        '#type' => 'fieldset',
        '#title' => $this->t('@label', ['@label' => $info['label']]),
        '#tree' => TRUE,
      ];
      $elements['variations'][$variation]['view_mode'] = [
        '#type' => 'select',
        '#options' => $options,
        '#title' => $this->t('View mode'),
        '#default_value' => $variations[$variation] ?? 'default',
        '#required' => TRUE,
      ];
    }

    return $elements;
  }

  /**
   * Get external entity resource display view mode options.
   *
   * @param string $variation
   *   The external entity variation.
   *
   * @return array
   *   An array of view mode options.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\external_entity\Exception\NotFoundResourceDisplayException
   */
  protected function getResourceDisplayViewModeOptions(
    string $variation,
  ): array {
    $render_type = $this->getResourceDisplayRenderType(
      $this->getExternalEntityResource(),
      $variation
    );

    return isset($render_type)
      ? $render_type->getRenderModes()
      : [];
  }

  /**
   * Get external entity display render type.
   *
   * @param string $type
   * @param string $variation
   *
   * @return \Drupal\external_entity\Contracts\ExternalEntityRenderTypeInterface
   *   The external entity render type instance.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\external_entity\Exception\NotFoundResourceDisplayException
   */
  protected function getResourceDisplayRenderType(
    string $type,
    string $variation,
  ): ?ExternalEntityRenderTypeInterface {
    return $this->getExternalEntityType()
      ->getResourceDisplay($type, $variation)
      ->createRenderInstance();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary(): array {
    $summary = [];

    foreach ($this->getSetting('variations') as $variation => $info) {
      $view_modes = $this->getResourceDisplayViewModeOptions($variation);

      if (!isset($info['view_mode'])) {
        continue;
      }
      $view_mode = $info['view_mode'];

      $summary[] = $this->t('Rendered using @mode for @variation.', [
        '@mode' => $view_modes[$view_mode] ?? $view_mode,
        '@variation' => $variation,
      ]);
    }

    return $summary;
  }

  /**
   * {@inheritDoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode): array {
    $variations = $this->getSetting('variations');
    $elements = [];

    /** @var \Drupal\external_entity\Contracts\ExternalEntityInterface $entity */
    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
      $view_mode = $variations[$entity->getVariation()]['view_mode'] ?? 'default';
      // Due to render caching and delayed calls, the viewElements() method
      // will be called later in the rendering process through a '#pre_render'
      // callback, so we need to generate a counter that takes into account
      // all the relevant information about this field and the referenced
      // entity that is being rendered.
      $recursive_render_id = $items->getFieldDefinition()->getTargetEntityTypeId()
        . $items->getFieldDefinition()->getTargetBundle()
        . $items->getName()
        // We include the referencing entity, so we can render default images
        // without hitting recursive protections.
        . $items->getEntity()->id()
        . $entity->getEntityTypeId()
        . $entity->id();

      if (isset(static::$recursiveRenderDepth[$recursive_render_id])) {
        static::$recursiveRenderDepth[$recursive_render_id]++;
      }
      else {
        static::$recursiveRenderDepth[$recursive_render_id] = 1;
      }

      // Protect ourselves from recursive rendering.
      if (static::$recursiveRenderDepth[$recursive_render_id] > static::RECURSIVE_RENDER_LIMIT) {
        $this->loggerFactory->get('entity')->error('Recursive rendering detected when rendering entity %entity_type: %entity_id, using the %field_name field on the %parent_entity_type:%parent_bundle %parent_entity_id entity. Aborting rendering.', [
          '%entity_type' => $entity->getEntityTypeId(),
          '%entity_id' => $entity->id(),
          '%field_name' => $items->getName(),
          '%parent_entity_type' => $items->getFieldDefinition()->getTargetEntityTypeId(),
          '%parent_bundle' => $items->getFieldDefinition()->getTargetBundle(),
          '%parent_entity_id' => $items->getEntity()->id(),
        ]);
        return $elements;
      }

      $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
      $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());

      // Add a resource attribute to set the mapping property's value to the
      // entity's url. Since we don't know what the markup of the entity will
      // be, we shouldn't rely on it for structured data such as RDFa.
      if (!empty($items[$delta]->_attributes) && !$entity->isNew() && $entity->hasLinkTemplate('canonical')) {
        $items[$delta]->_attributes += ['resource' => $entity->toUrl()->toString()];
      }
    }

    return $elements;
  }

  /**
   * {@inheritDoc}
   */
  public static function isApplicable(
    FieldDefinitionInterface $field_definition,
  ): bool {
    $interface = EntityReferenceFieldItemListInterface::class;
    return parent::isApplicable($field_definition)
      && is_subclass_of($field_definition->getClass(), $interface)
      && $field_definition->getSetting('target_type') === 'external_entity';
  }

  /**
   * Get the field reference handler settings.
   *
   * @return array
   *   An array of the reference handle settings.
   */
  protected function getFieldHandlerSettings(): array {
    return $this->getFieldSetting('handler_settings') ?? [];
  }

  /**
   * Get external entity resource.
   *
   * @return string|null
   *   The external entity resource name.
   */
  protected function getExternalEntityResource(): ?string {
    return $this->getFieldHandlerSettings()['resource'] ?? NULL;
  }

  /**
   * Get the external entity resource variations.
   *
   * @return array
   *   An array of external entity resource variations.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  protected function getExternalEntityResourceVariations(): array {
    return $this->getExternalEntityType()->getResourceVariations(
      $this->getExternalEntityResource()
    );
  }

  /**
   * Get the external entity type.
   *
   * @return \Drupal\external_entity\Contracts\ExternalEntityTypeInterface
   *   The external entity type.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getExternalEntityType(): ExternalEntityTypeInterface {
    return $this->getExternalEntityTypeStorage()->load(
      $this->getFieldHandlerSettings()['type'] ?? NULL
    );
  }

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

}

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

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