You are here

public function ImageViewBuilder::build in Twig Tweak 3.1.x

Same name and namespace in other branches
  1. 3.x src/View/ImageViewBuilder.php \Drupal\twig_tweak\View\ImageViewBuilder::build()

Builds an image.

Parameters

\Drupal\file\FileInterface $file: The file object.

string $style: (optional) Image style.

array $attributes: (optional) Image attributes.

bool $responsive: (optional) Indicates that the provided image style is responsive.

bool $check_access: (optional) Indicates that access check is required.

Return value

array A renderable array to represent the image.

File

src/View/ImageViewBuilder.php, line 31

Class

ImageViewBuilder
Image view builder.

Namespace

Drupal\twig_tweak\View

Code

public function build(FileInterface $file, string $style = NULL, array $attributes = [], bool $responsive = FALSE, bool $check_access = TRUE) : array {
  $access = $check_access ? $file
    ->access('view', NULL, TRUE) : AccessResult::allowed();
  $build = [];
  if ($access
    ->isAllowed()) {
    $build['#uri'] = $file
      ->getFileUri();
    $build['#attributes'] = $attributes;
    if ($style) {
      if ($responsive) {
        $build['#type'] = 'responsive_image';
        $build['#responsive_image_style_id'] = $style;
      }
      else {
        $build['#theme'] = 'image_style';
        $build['#style_name'] = $style;
      }
    }
    else {
      $build['#theme'] = 'image';
    }
  }
  CacheableMetadata::createFromRenderArray($build)
    ->merge(CacheableMetadata::createFromObject($access))
    ->applyTo($build);
  return $build;
}