I'm running into a problem creating a URL to an unmanaged file in the "public" file directory (this is for the file_example for Drupal 8).
The following code will throw an exception:
use Drupal\Core\Url;
$stuff = "content for an unmanaged file\n";
$dest = file_unmanaged_save_data($data, "public://unmanaged-mahem.txt");
print "URI: $dest\n";
$url = Url::fromUri($dest);
$our_uri = $url->getUri();
print "Our URL was created, and thinks it corresponds to the URI $our_uri\n";
//but this throws:
$external_link = \Drupal::l(t('External link'), $url);
print "External Link: $external_link\n";
When run, here's what you see (the stack trace is removed):
$ drush @d8 scr unmanaged-mahem.php
URI: public://unmanaged-mahem_1.txt
Our URL was created, and thinks it corresponds to the URI public://unmanaged-mahem.txt
exception 'InvalidArgumentException' with message 'The URI 'public://unmanaged-mahem_1.txt' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal
paths controlled by Drupal.' in /var/www/drupal/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php:69
I'm not sure if this is a bug or if this is by design, since in general, you'd want to use a managed file for anything in the public files directory that was for public consumption. But the change record doesn't say anything about this.
Is there a valid way to create a link to an unmanaged file in Drupal 8?