external_entity-1.0.x-dev/src/Entity/ExternalEntityViewBuilder.php

src/Entity/ExternalEntityViewBuilder.php
<?php

declare(strict_types=1);

namespace Drupal\external_entity\Entity;

use Drupal\Component\Utility\DeprecationHelper;
use Drupal\Core\Utility\Error;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityHandlerBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterPluginManager;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\external_entity\Contracts\ExternalEntityInterface;
use Drupal\external_entity\Contracts\ExternalEntityTypeInterface;
use Drupal\external_entity\Exception\NotFoundResourceDisplayException;
use Drupal\external_entity\Contracts\ExternalEntityViewBuilderInterface;
use Drupal\external_entity\Contracts\ExternalEntityResourceDisplayInterface;

/**
 * Define the external entity view builder.
 */
class ExternalEntityViewBuilder extends EntityHandlerBase implements ExternalEntityViewBuilderInterface {

  /**
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityType;

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

  /**
   * @var \Drupal\Core\Field\FormatterPluginManager
   */
  protected $fieldFormatterManager;

  /**
   * Define the class constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type instance.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Field\FormatterPluginManager $field_formatter_manager
   *   The field formatter manager.
   */
  public function __construct(
    EntityTypeInterface $entity_type,
    EntityTypeManagerInterface $entity_type_manager,
    FormatterPluginManager $field_formatter_manager,
  ) {
    $this->entityType = $entity_type;
    $this->entityTypeManager = $entity_type_manager;
    $this->fieldFormatterManager = $field_formatter_manager;
  }

  /**
   * {@inheritDoc}
   */
  public static function createInstance(
    ContainerInterface $container,
    EntityTypeInterface $entity_type,
  ) {
    return new static(
      $entity_type,
      $container->get('entity_type.manager'),
      $container->get('plugin.manager.field.formatter')
    );
  }

  /**
   * {@inheritDoc}
   */
  public function buildComponents(
    array &$build,
    array $entities,
    array $displays,
    $view_mode,
  ): void {}

  /**
   * {@inheritDoc}
   */
  public function view(
    EntityInterface $entity,
    $view_mode = 'full',
    $langcode = NULL,
  ): array {
    $output = [];
    /** @var \Drupal\external_entity\Entity\ExternalEntity $entity */
    try {
      $display = $this->getResourceDisplay(
        $entity->getResource(),
        $entity->getVariation(),
        $entity->getBundleEntityType()
      );
      $output = $display->createRenderInstance()->render(
        $entity,
        $view_mode
      );
    }
    catch (\Exception $exception) {
      DeprecationHelper::backwardsCompatibleCall(\Drupal::VERSION, '10.1.0', fn() => Error::logException(\Drupal::logger('external_entity'), $exception), fn() => watchdog_exception('external_entity', $exception));
    }

    return $output;
  }

  /**
   * {@inheritDoc}
   */
  public function viewMultiple(
    array $entities = [],
    $view_mode = 'full',
    $langcode = NULL,
  ): array {
    return [];
  }

  /**
   * {@inheritDoc}
   */
  public function resetCache(?array $entities = NULL): void {}

  /**
   * {@inheritDoc}
   */
  public function viewField(
    FieldItemListInterface $items,
    $display_options = [],
  ): array {
    $items->filterEmptyItems();

    $options = [
      'prepare' => TRUE,
      'view_mode' => 'default',
      'configuration' => $display_options,
      'field_definition' => $items->getFieldDefinition(),
    ];
    $formatter = $this->fieldFormatterManager->getInstance($options);
    $formatter->prepareView([$items]);

    $output = $formatter->view($items);
    $output['#label_display'] = 'hidden';

    return $output;
  }

  /**
   * {@inheritDoc}
   */
  public function viewFieldItem(
    FieldItemInterface $item,
    $display_options = [],
  ): array {
    $output = $elements[0] ?? [];
    $entity = $item->getEntity();

    $field_name = $item->getFieldDefinition()->getName();
    $clone = clone $entity;

    $clone->{$field_name}->setValue([$item->getValue()]);
    $elements = $this->viewField($clone->{$field_name}, $display_options);

    if (isset($elements['#access'])) {
      $output['#access'] = $elements['#access'];
    }

    return $output;
  }

  /**
   * {@inheritDoc}
   */
  public function getCacheTags(): array {
    return [];
  }

  /**
   * {@inheritDoc}
   */
  public function createProxyEntity(
    ExternalEntityInterface $entity,
  ): ?EntityInterface {
    $display = $this->getResourceDisplay(
      $entity->getResource(),
      $entity->getVariation(),
      $entity->getBundleEntityType()
    );

    return $display->createRenderInstance()->createEntity(
      $entity
    );
  }

  /**
   * Get the external entity resource display.
   *
   * @param string $resource
   *   The external resource name.
   * @param string $variation
   *   The external resource variation.
   * @param \Drupal\external_entity\Contracts\ExternalEntityTypeInterface $bundle
   *
   * @return \Drupal\external_entity\Contracts\ExternalEntityResourceDisplayInterface|null
   *   The related resource display instance.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\external_entity\Exception\NotFoundResourceDisplayException
   */
  protected function getResourceDisplay(
    string $resource,
    string $variation,
    ExternalEntityTypeInterface $bundle,
  ): ?ExternalEntityResourceDisplayInterface {
    $display = $bundle->getResourceDisplay($resource, $variation);

    if (!isset($display)) {
      throw new NotFoundResourceDisplayException(
        $resource, $variation
      );
    }

    return $display;
  }

  /**
   * External entity resource display storage.
   *
   * @return \Drupal\Core\Entity\EntityStorageInterface
   *   The entity storage instance.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function externalEntityResourceDisplayStorage(): EntityStorageInterface {
    return $this->entityTypeManager->getStorage('external_entity_resource_display');
  }

}

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

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