You are here

private function HierarchicalTaxonomyMenuBlock::getImageFromTid in Hierarchical Taxonomy Menu 8

Gets image from term.

1 call to HierarchicalTaxonomyMenuBlock::getImageFromTid()
HierarchicalTaxonomyMenuBlock::build in src/Plugin/Block/HierarchicalTaxonomyMenuBlock.php
Builds and returns the renderable array for this block plugin.

File

src/Plugin/Block/HierarchicalTaxonomyMenuBlock.php, line 742

Class

HierarchicalTaxonomyMenuBlock
Provides a 'HierarchicalTaxonomyMenuBlock' block.

Namespace

Drupal\hierarchical_taxonomy_menu\Plugin\Block

Code

private function getImageFromTid($tid, $image_field, $image_style) {
  if (!is_numeric($tid) || $image_field == '') {
    return '';
  }
  if (isset(self::$terms[$tid])) {
    $term = self::$terms[$tid];
  }
  else {
    $term = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->load($tid);
    self::$terms[$tid] = $term;
  }
  $image_field_name = $term
    ->get($image_field)
    ->getValue();
  $image_field_type = $term
    ->get($image_field)
    ->getFieldDefinition()
    ->getType();
  if (!isset($image_field_name[0]['target_id'])) {
    return '';
  }
  if ($image_field_type == 'image') {
    $fid = $image_field_name[0]['target_id'];
  }
  else {

    // A field of media type.
    $fid = FALSE;
    foreach ($image_field_name as $value) {
      $media = $value['target_id'];
      $media = $this->entityTypeManager
        ->getStorage('media')
        ->load($media);
      if ($media && $media
        ->bundle() == 'image') {
        foreach ($media
          ->referencedEntities() as $item) {
          if ($item
            ->getEntityTypeId() == 'file') {
            $fid = $item
              ->id();
            break;
          }
        }
      }
      if ($fid) {
        break;
      }
    }
  }
  if ($fid) {
    $file = $this->entityTypeManager
      ->getStorage('file')
      ->load($fid);
    if ($image_style) {
      $style = $this->entityTypeManager
        ->getStorage('image_style')
        ->load($image_style);
      if ($style) {
        $path = $style
          ->buildUrl($file
          ->getFileUri());
      }
      else {
        $path = Url::fromUri(file_create_url($file
          ->getFileUri()));
      }
    }
    else {
      $path = Url::fromUri(file_create_url($file
        ->getFileUri()));
    }
    return $path;
  }
  return '';
}