How do I programmatically create a file and write it in the private:// folder?
Pergunta
How do I programmatically create a text file and write to it in the private:// folder in Drupal 8.8? I found some examples, but all of them use deprecated functions and they don't work.
Here what I have now, but i't s not creating folder and text file in it with content:
use Drupal\Core\StreamWrapper\PrivateStream;
...
...
$output = 'Test Text';
$file_save_path_stream_directory = 'private://gmt';
file_prepare_directory($file_save_path_stream_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$fileLocation = $file_save_path_stream_directory . '/test.txt';
$file = file_save_data($output, $fileLocation, FILE_EXISTS_REPLACE);
Solução
If anyone need it, I make it work:
use Drupal\Core\File\FileSystemInterface;
...
/**
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
public function __construct(FileSystemInterface $fileSystem) {
$this->fileSystem = $fileSystem;
}
public function testCreation() {
$request = 'test content';
$path = 'private://gmt/';
if ($this->fileSystem->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY)) {
/** @var \Drupal\file\FileInterface $file */
$file = file_save_data(
$request,
$path . 'requests.txt'
);
}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a drupal.stackexchange