a12s-1.0.0-beta7/src/EntityHelper.php

src/EntityHelper.php
<?php

namespace Drupal\a12s_core;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\Core\Utility\Error;

/**
 * The "Entity Helper" service.
 */
class EntityHelper implements EntityHelperInterface {

  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected RouteMatchInterface $routeMatch
  ) {}

  /**
   * {@inheritDoc}
   */
  public function entityGetField(FieldableEntityInterface $entity, string $fieldName): ?FieldItemListInterface {
    if ($entity->hasField($fieldName) && !$entity->get($fieldName)->isEmpty()) {
      return $entity->get($fieldName);
    }

    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function entityGetFieldReferenceEntity(FieldableEntityInterface $entity, string $fieldName, int $delta = 0): ?EntityInterface {
    $erField = $this->entityGetField($entity, $fieldName);

    if ($erField && $erField->offsetExists($delta)) {
      try {
        /** @var \Drupal\Core\Field\FieldItemListInterface $item */
        $item = $erField->get($delta);
        /** @noinspection PhpExpressionAlwaysNullInspection */
        return $item->entity ?? NULL;
      }
      catch (MissingDataException $e) {
        Error::logException(\Drupal::logger('a12s_core'), $e);
      }
    }

    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function entityGetFieldReferenceSubField(FieldableEntityInterface $entity, string $erFieldName, string $fieldName, int $erDelta = 0): ?FieldItemListInterface {
    $subEntity = $this->entityGetFieldReferenceEntity($entity, $erFieldName, $erDelta);
    return $subEntity instanceof FieldableEntityInterface ? $this->entityGetField($subEntity, $fieldName) : NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function entityGetFieldValue(FieldableEntityInterface $entity, string $fieldName, int $delta = 0, ?string $property = NULL): mixed {
    if ($item_list = $this->entityGetField($entity, $fieldName)) {
      try {
        $value = $item_list->get($delta)->getValue();

        if (!isset($property)) {
          return $value;
        }

        if (is_array($value) && array_key_exists($property, $value)) {
          return $value[$property];
        }
      }
      catch (MissingDataException $e) {
        Error::logException(\Drupal::logger('a12s'), $e);
      }
    }

    return NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function renderEntity(EntityInterface $entity, string $viewMode = 'full', ?string $langCode = NULL): array {
    $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
    return $view_builder->view($entity, $viewMode, $langCode);
  }

  /**
   * {@inheritDoc}
   */
  public function isViewModeEnabled(EntityInterface $entity, string $viewMode = 'full'): bool {
    $display = $this->loadEntityViewDisplay($entity->getEntityTypeId(), $entity->bundle(), $viewMode);
    return $display && $display->status();
  }

  /**
   * {@inheritDoc}
   */
  public function renderEntityIfViewModeEnabled(EntityInterface $entity, string $viewMode = 'full', ?string $langCode = NULL): array {
    return $this->isViewModeEnabled($entity, $viewMode) ? $this->renderEntity($entity, $viewMode) : [];
  }

  /**
   * {@inheritDoc}
   */
  public function loadEntityViewDisplay(string $entityType, string $bundle, string $viewMode = EntityDisplayRepositoryInterface::DEFAULT_DISPLAY_MODE): EntityViewDisplayInterface|EntityInterface|null {
    try {
      return $this->entityTypeManager
        ->getStorage('entity_view_display')
        ->load($entityType . '.' . $bundle . '.' . $viewMode);
    }
    catch (\Exception $e) {
      return NULL;
    }
  }

  /**
   * {@inheritDoc}
   */
  public function getEntityFromRoute(?string $rel = 'canonical'): ?ContentEntityBase {
    static $drupalStaticFast;

    if (!isset($drupalStaticFast)) {
      $drupalStaticFast['entity'] = &drupal_static('a12s_core_entity_helper_entity_from_route', []);
    }

    if (!array_key_exists($rel, $drupalStaticFast['entity'])) {
      $drupalStaticFast['entity'][$rel] = NULL;

      if ($routeName = $this->routeMatch->getRouteName()) {
        // Are we displaying an entity canonical page?
        if ($entityType = $this->getEntityTypeFromRoute($routeName, $rel)) {
          // Look for a fieldable entity of the expected type.
          foreach ($this->routeMatch->getParameters() as $parameter) {
            if ($parameter instanceof ContentEntityBase && $parameter->getEntityTypeId() === $entityType) {
              $drupalStaticFast['entity'][$rel] = $parameter;
              break;
            }
          }
        }
      }
    }

    return $drupalStaticFast['entity'][$rel];
  }

  /**
   * {@inheritDoc}
   */
  public function getEntityTypeFromRoute(string $routeName, ?string $rel = 'canonical'): ?string {
    $match = [];
    if (preg_match('/^entity\.(?P<entity_type>[^\.]+)\.' . preg_quote($rel, '/') . '$/', $routeName, $match)) {
      return $match['entity_type'];
    }

    return NULL;
  }

}

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

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