Change record status: 
Project: 
Introduced in branch: 
9.3.x
Introduced in version: 
9.3.0
Description: 

file_save_data, file_copy and file_move are deprecated and replaced with a service that implements \Drupal\file\FileRepositoryInterface.

Before After
file_save_data() \Drupal::service('file.repository')->writeData()
file_move() \Drupal::service('file.repository')->move()
file_copy() \Drupal::service('file.repository')->copy()

The method arguments are the same except now $destination is now a required argument. When the $destination was not set it would get the default value from \Drupal::config('system.file')->get('default_scheme') . '://', which would normally result in the string public://.

The new service has also adds the method called: loadByUri(string $uri) which loads the first File entity found with the specified URI.

The new methods do not handle logging messages nor displaying flash messages using Drupal::messenger(). Calling code should handle this if needed.

These methods also now throw the following exceptions:

  • \Drupal\Core\File\Exception\FileException: Thrown when there is an error writing to the file system.
  • \Drupal\Core\File\Exception\InvalidStreamWrapperException: Thrown when the destination is an invalid stream wrapper.
  • \Drupal\Core\Entity\EntityStorageException: Thrown when there is an error updating the file storage.
Impacts: 
Module developers

Comments

firfin’s picture

So for example
file_copy( $imgFile,'public://', FileSystemInterface::EXISTS_REPLACE );
gets replaced with
$imgFile = \Drupal::service('file.repository')->copy( $imgFile,'public://', FileSystemInterface::EXISTS_REPLACE );

And
$file = file_save_data($handle, 'public://$value');
becomes
$file = \Drupal::service('file.repository')->writeData($handle, 'public://$value');