Drupal – Extract file url from media entity
     发布在:PHP      浏览:13      评论:0 条评论

A useful function would be to extract the File URL from a Media Entity.

/**
 * Implements hook_preprocess_entity_embed_container().
 */
function demo_preprocess_entity_embed_container__media__document(&$variables) {
  if (isset($variables['element']['#entity'])) {
    $media = $variables['element']['#entity'];
    $source = $media->getSource();

    $source_field = $source->getSourceFieldDefinition($media->bundle->entity)->getName();
    $source_field_item = $media->get($source_field)->first();

    if ($source_field_item) {
      $source_value = $source->getSourceFieldValue($media);
      $file = $source_value ? File::load($source_value) : NULL;
      $url = $file ? $file->createFileUrl(FALSE) : NULL;

      if ($url) {
        $label = html_entity_decode($media->label());
        $mime_type = $file->getMimeType();
        $variables['document'] = [
          'name' => $file->getFilename(),
          'label' => $label,
          'url' => $url,
          'link' => _make_link_by_file($label, $file),
          'type' => $mime_type . '; length=' . $file->getSize(),
          'classes' => _make_classes_by_mime_type($mime_type),
        ];
      }
    }
  }
}

/**
 * Make drupal link by file.
 */
function _make_link_by_file($link_text, File $file) {
  $options = [];
  $mime_type = $file->getMimeType();
  $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();
  $options['attributes']['title'] = $link_text;
  $options['attributes']['class'] = _make_classes_by_mime_type($mime_type);
  $options['attributes']['target'] = '_blank';
  return \Drupal::l($link_text, Url::fromUri($file->createFileUrl(FALSE), $options));
}

/**
 * Make classes by file mime type.
 */
function _make_classes_by_mime_type($mime_type) {
  // Classes to add to the file field for icons.
  $classes = [
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, [
      '/' => '-',
      '.' => '-',
    ]),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  ];

  if (file_icon_class($mime_type) == 'application-pdf') {
    array_push($classes, 'comPdf');
  }

  return $classes;
}
    Responses