You are here

public function PhotosAlbum::getCover in Album Photos 6.0.x

Same name and namespace in other branches
  1. 8.5 src/PhotosAlbum.php \Drupal\photos\PhotosAlbum::getCover()
  2. 8.4 src/PhotosAlbum.php \Drupal\photos\PhotosAlbum::getCover()

Get album cover.

Parameters

int $cover_id: The photos_image entity id.

bool $uri_only: Return image URI only if available (used for photos album media).

Return value

array Render array.

File

src/PhotosAlbum.php, line 221

Class

PhotosAlbum
Create an album object.

Namespace

Drupal\photos

Code

public function getCover($cover_id = NULL, $uri_only = FALSE) {
  $albumId = $this->albumId;
  $cover = [];
  if (!$cover_id) {

    // Check album for cover fid.
    $db = \Drupal::database();
    $cover_id = $db
      ->query("SELECT cover_id FROM {photos_album} WHERE album_id = :album_id", [
      ':album_id' => $albumId,
    ])
      ->fetchField();
  }

  // If id is still empty.
  if (empty($cover_id)) {

    // Cover not set, select an image from the album.
    $db = \Drupal::database();
    $query = $db
      ->select('photos_image_field_data', 'p');
    $query
      ->fields('p', [
      'id',
    ]);
    $query
      ->condition('p.album_id', $albumId);
    $cover_id = $query
      ->execute()
      ->fetchField();
  }
  if ($cover_id) {

    // Load image.
    $photos_image = NULL;
    try {
      $photos_image = \Drupal::entityTypeManager()
        ->getStorage('photos_image')
        ->load($cover_id);
    } catch (InvalidPluginDefinitionException $e) {
      watchdog_exception('photos', $e);
    } catch (PluginNotFoundException $e) {
      watchdog_exception('photos', $e);
    }
    if ($photos_image) {
      if ($uri_only) {
        if ($photos_image
          ->hasField('field_image') && $photos_image->field_image->entity) {
          $cover = $photos_image->field_image->entity
            ->getFileUri();
        }
      }
      else {
        $cover = \Drupal::entityTypeManager()
          ->getViewBuilder('photos_image')
          ->view($photos_image, 'cover');
      }
    }
  }
  return $cover;
}