You are here

public static function TwigTweakExtension::drupalImage in Twig Tweak 3.x

Same name and namespace in other branches
  1. 3.1.x src/TwigTweakExtension.php \Drupal\twig_tweak\TwigTweakExtension::drupalImage()

Builds an image.

File

src/TwigTweakExtension.php, line 230

Class

TwigTweakExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public static function drupalImage(string $selector, string $style = NULL, array $attributes = [], bool $responsive = FALSE, bool $check_access = TRUE) : array {

  // Determine selector type by its value.
  if (preg_match('/^\\d+$/', $selector)) {
    $selector_type = 'fid';
  }
  elseif (Uuid::isValid($selector)) {
    $selector_type = 'uuid';
  }
  else {
    $selector_type = 'uri';
  }
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties([
    $selector_type => $selector,
  ]);

  // To avoid ambiguity render nothing unless exact one image has been found.
  if (count($files) != 1) {
    return [];
  }
  $file = reset($files);
  return \Drupal::service('twig_tweak.image_view_builder')
    ->build($file, $style, $attributes, $responsive, $check_access);
}