You are here

class FieldViewBuilder in Twig Tweak 3.1.x

Same name and namespace in other branches
  1. 3.x src/View/FieldViewBuilder.php \Drupal\twig_tweak\View\FieldViewBuilder

Field view builder.

Hierarchy

Expanded class hierarchy of FieldViewBuilder

1 string reference to 'FieldViewBuilder'
twig_tweak.services.yml in ./twig_tweak.services.yml
twig_tweak.services.yml
1 service uses FieldViewBuilder
twig_tweak.field_view_builder in ./twig_tweak.services.yml
Drupal\twig_tweak\View\FieldViewBuilder

File

src/View/FieldViewBuilder.php, line 13

Namespace

Drupal\twig_tweak\View
View source
class FieldViewBuilder {

  /**
   * The entity repository.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * Constructs a FieldViewBuilder object.
   */
  public function __construct(EntityRepositoryInterface $entity_repository) {
    $this->entityRepository = $entity_repository;
  }

  /**
   * Returns the render array for a single entity field.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   * @param string $field_name
   *   The field name.
   * @param string|array $view_mode
   *   (optional) The view mode that should be used to render the field.
   * @param string $langcode
   *   (optional) Language code to load translation.
   * @param bool $check_access
   *   (optional) Indicates that access check is required.
   *
   * @return array
   *   A render array for the field.
   */
  public function build(EntityInterface $entity, string $field_name, $view_mode = 'full', string $langcode = NULL, bool $check_access = TRUE) : array {
    $build = [];
    $entity = $this->entityRepository
      ->getTranslationFromContext($entity, $langcode);
    $access = $check_access ? $entity
      ->access('view', NULL, TRUE) : AccessResult::allowed();
    if ($access
      ->isAllowed()) {
      if (!isset($entity->{$field_name})) {

        // @todo Trigger error here.
        return [];
      }
      $build = $entity->{$field_name}
        ->view($view_mode);
    }
    CacheableMetadata::createFromRenderArray($build)
      ->merge(CacheableMetadata::createFromObject($access))
      ->merge(CacheableMetadata::createFromObject($entity))
      ->applyTo($build);
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FieldViewBuilder::$entityRepository protected property The entity repository.
FieldViewBuilder::build public function Returns the render array for a single entity field.
FieldViewBuilder::__construct public function Constructs a FieldViewBuilder object.