Skip to content

Instantly share code, notes, and snippets.

@arlina-espinoza
Last active August 24, 2023 20:27
Show Gist options
  • Save arlina-espinoza/6e0d0f8f84ded0acb2671e272acb835d to your computer and use it in GitHub Desktop.
Save arlina-espinoza/6e0d0f8f84ded0acb2671e272acb835d to your computer and use it in GitHub Desktop.
Drupal 9-10: Save dynamically generated files
<?php
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Serialization\Yaml;
function saveFileDirectly($data) {
$encoded = Yaml::encode($data);
$filename = 'public://my_dir/my_file.yaml';
// Get the folder for the final location of this style.
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$directory = $file_system->dirname($filename);
$file_system->prepareDirectory($directory, FileSyste mInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
// Save file directly - not invoking hooks or logging in the file_managed table.
$path = $file_system->saveData($encoded, $filename, FileSystemInterface::EXISTS_REPLACE);
return $path;
}
function saveFileInManagedFiles($data, NodeInterface $entity) {
$encoded = Yaml::encode($data);
$filename = 'public://my_dir/my_file.yaml';
/** @var \Drupal\file\FileRepositoryInterface $fileRepository */
$fileRepository = \Drupal::service('file.repository');
$file = $fileRepository->writeData($encoded, $filename, FileSystemInterface::EXISTS_REPLACE);
$file->save();
/** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'icims_core', 'node', $entity->id());
return $filename;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment