Skip to content

Move preprocess_file_link() to localgov_core #850

@markconroy

Description

@markconroy

If we move the following code to LocalGov Core, then any document media items that we have will display the same in the backend and the frontend.

At the moment, if we merge #849 then in our editor screens we will see for example my-file.pdf (PDF, 2MB) but on the frontend we will see My File (PDF, 2MB).

Moving this will mean we have a consistent experience for all whether using LocalGov Base or not.

/**
 * Implements hook_preprocess_file_link().
 *
 * Changes:
 * - Inserts file *type* and size into the theme variable.
 * - Reformats file size.  Example: 123.4KB.
 * - Appends file metadata to the file link text.
 *
 * @see template_preprocess_file_link()
 */
function localgov_base_preprocess_file_link(&$variables): void {

  $file = $variables['file'];
  $filename = $file->getFilename();
  $file_extension = pathinfo($filename, PATHINFO_EXTENSION);

  $variables['file_type'] = strtoupper($file_extension);

  // 123.45 KB -> 123.45KB
  $variables['file_size'] = strtr($variables['file_size'], [' ' => '']);

  // Load media entity from file.
  $media_id = $file->_referringItem->getParent()->getParent()->getEntity()->get('mid')->getString();
  $media = \Drupal\media\Entity\Media::load($media_id);
  $media_name = $media->get('name')->getString();

  if (isset($variables['link']['#title'])) {
    $document_title = $variables['link']['#title'];

    if ($media_name && $media_name !== $document_title) {
      // If the media name is set and different to the $variables['link']['#title'],
      // we will use that instead.
      $document_title = $media_name;
    }

    $variables['link']['#title'] = [
      '#markup' => "{$document_title} <span class=\"file-meta\">(<span class=\"file-type\">{$variables['file_type']}</span>, <span class=\"file-size\">{$variables['file_size']}</span>)</span>",
    ];
  }
  else {
    $file_title = $variables['link'];
    $variables['link'] = [
      '#markup' => "{$file_title} <span class=\"file-meta\">(<span class=\"file-type\">{$variables['file_type']}</span>, <span class=\"file-size\">{$variables['file_size']}</span>)</span>",
    ];
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions