You are here

public function PhotosImage::view in Album Photos 8.5

Same name and namespace in other branches
  1. 8.4 src/PhotosImage.php \Drupal\photos\PhotosImage::view()

Return render array to view image.

Parameters

string $style_name: The image style machine name.

array $variables: (Optional) variables to override image defaults:

  • 'title': image title and alt if alt is empty.
  • 'href': image link href.

Return value

array Render array for image view.

File

src/PhotosImage.php, line 78

Class

PhotosImage
Create images object.

Namespace

Drupal\photos

Code

public function view($style_name = NULL, array $variables = []) {
  $image = $this
    ->load();
  if (isset($variables['title'])) {
    $image->title = $variables['title'];
  }
  if (!$style_name) {

    // Get thumbnail image style from admin settings.
    $image_sizes = \Drupal::config('photos.settings')
      ->get('photos_size');
    $style_name = key($image_sizes);
  }
  if (!$style_name) {

    // Fallback on default thumbnail style.
    $style_name = 'thumbnail';
  }

  // Check scheme and prep image.
  $scheme = \Drupal::service('stream_wrapper_manager')
    ->getScheme($image->uri);
  $uri = $image->uri;

  // If private create temporary derivative.
  if ($scheme == 'private') {
    $photos_image = new PhotosImage($image->fid);
    $url = $photos_image
      ->derivative($uri, $style_name, $scheme);
  }
  else {

    // Public and all other images.
    $style = ImageStyle::load($style_name);
    $url = $style
      ->buildUrl($uri);
  }

  // Build image render array.
  $title = isset($image->title) ? $image->title : '';
  $alt = isset($image->alt) ? $image->alt : $title;
  $image_render_array = [
    '#theme' => 'image',
    '#uri' => $url,
    '#alt' => $alt,
    '#title' => $title,
  ];
  if (isset($variables['href'])) {
    $image_render_array = [
      '#type' => 'link',
      '#title' => $image_render_array,
      '#url' => Url::fromUri('base:' . $variables['href']),
    ];
  }
  return $image_render_array;
}