By kim.pepper on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
10.2.x
Introduced in version:
10.2.0
Issue links:
Description:
system_retrieve_file() has been deprecated. New code should use one of the Drupal services for file operations.
Calling code should handle exceptions and set flash messages or logging as required.
Before:
<?php
$file = system_retrieve_file($url, $destination, $managed, $replace);
?>
After:
<?php
use Drupal\Core\File\FileExists;
use Drupal\Core\FileTransfer\FileTransferException;
use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\Exception\InvalidStreamWrapperException;
try {
$data = (string) \Drupal::httpClient()->get($url)->getBody();
// Use the correct service depending on whether you want a managed file or not.
// For unmanaged files, use this:
$file = \Drupal::service('file_system')->saveData($data, $destination, FileExists::Replace);
// For managed files, use this:
$file = \Drupal::service('file.repository')->writeData($data, $destination, FileExists::Replace);
}
catch (FileTransferException $e) {
\Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $e->getMessage()]));
}
catch (FileException | InvalidStreamWrapperException $e) {
\Drupal::messenger()->addError(t('Failed to save file due to error "%error"', ['%error' => $e->getMessage()]));
}
?>
Impacts:
Module developers
Comments
Saving managed files
We could not find
\Drupal\file\ManagedFileFetcherorfile.fetcher.managedbut it appears that thefile.repositoryservice will do what we need.Also, could not find
TransferExceptionbutFileTransferExceptionappears to be the replacement.TransferException is part of
TransferException is part of the Guzzle library
use GuzzleHttp\Exception\TransferException
Error with suggested code
Hi team
After replacing
with
in my custom function , the $destination does not generate a proper output.
Incorrect instructions for replacement
The message here is pretty bizarre, neither of the two classes suggested as replacements exist in Drupal, and are not used in the sample code. Please consider editing this to avoid confusion.
I agree with @dafeder, the
I agree with @dafeder, the code sample contained several problems. I've updated the page to correct these issues.