This answer is tested with Drupal 9.3 and doesn't use file_save_data()
, which is deprecated in 9.3 and will be removed in Drupal 10.
use Drupal\Core\File\FileSystemInterface;
...
/**
* Provides helpers to operate on files and stream wrappers.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* Constructs an object.
*
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system manager.
*/
public function __construct(FileSystemInterface $file_system) {
$this->fileSystem = $file_system;
}
public function testFunction($data, $destination) {
if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
// @todo Log an error.
return FALSE;
}
$this->fileSystem->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
// Create and save a new file entity.
// @see FileRepository::createOrUpdate().
$new_file = File::create(['uri' => $file->uri]);
$new_file->setOwnerId(1);
$new_file->setPermanent();
$new_file->save();
return $new_file;
}
It should also be noted that in Drupal 9.3, though $data
can be a file handle resource
passed to fileSystem->saveData()
, it is not documented and doesn't have test coverage. file_save_data()
also allowed a resource
data parameter. FileRepository::writeData()
does not allow one, however, although that's only because it specifies string $data
in the function declaration.
$file
after the call? Have you checked the function docs to see what that would suggest?