How would you convert a link to a media item to the file URL in a menu? I would like to be able to link to media in a Drupal menu and have the link converted to a file url.  Is this possible?
I came up with a solution, where you add the link like this: '/media/1234'

And then add this code:

function mymodule_link_alter(&amp;$variables) {
  $url = $variables['url'];

  if (!$url-&gt;isRouted() &amp;&amp; $uri = $variables['url']-&gt;getUri()) {
    preg_match('/base\:media\/(\d+)/', $variables['url']-&gt;getUri(), $match);
    if (!empty($match) &amp;&amp; !empty($match[1])) {
      $media = \Drupal::entityTypeManager()-&gt;getStorage('media')-&gt;load($match[1]);
      if (!empty($media) &amp;&amp; $media-&gt;bundle() === 'document') {
        if ($file = $media-&gt;field_media_file-&gt;entity) {
          $variables['url'] = Url::fromUri(file_create_url($file-&gt;getFileUri()), $url-&gt;getOptions());
        }
      }
    }
  }
}


I hardcoded the source field.  You could make it more generic if you like.