How can I override template_preprocess_file_link function? I want to print file size near file link in file-link.html.twig template.
To do so I need something like {{ filesize }} variable avaiable in template.

I tried to override template_preprocess_file_link() with an override function in mytheme.theme like mytheme_preprocess_file_link() but I get this error:

The website encountered an unexpected error. Please try again later.
Error: Class 'File' not found in tofacile_preprocess_file_link() (line 12 of themes/custom/mytheme/mytheme.theme)


It seems like a class missing... should I add "use Drupal\File\SomethingXXX" declaration??

Thanks

This is my code:

&lt;?php

/**
 * @file
 * Functions to support theming in the Tofacile theme.
 */


function tofacile_preprocess_file_link(&amp;$variables){
  $file = $variables['file'];
  $options = [];
  $file_entity = $file instanceof File ? $file : File::load($file-&gt;fid);

  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity
    -&gt;getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';
  $mime_type = $file
    -&gt;getMimeType();

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file
      -&gt;getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file_entity
      -&gt;getFilename();
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity
      -&gt;getFilename();
  }

  // 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, [
      '/' =&gt; '-',
      '.' =&gt; '-',
    ]),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  ];

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']
    -&gt;addClass($classes);
  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}
Yes, seems you need to add:

use Drupal\file\Entity\File;


to the begin of your mytheme.theme file. You can also do something like:

$file_entity = $file instanceof \Drupal\file\Entity\File ? $file : 
\Drupal\file\Entity\File::load($file-&gt;fid);


And you will have the same problem with Attribute and Url. You need to import the classes with the complet namespace in your file. https://secure.php.net/manual/en/language.namespaces.importing.php