I'm trying to create an archive of log files to be downloadable in a form making a custom module in Drupal 9.
In the form, the user can change the format of the archive, as per image:
Here below my code:
private function download($form, $form_state) {
$format = $form_state->getValue('format');
$folder = $form_state->getValue('folders');
$date = new DateTime();
$date = $date->format("y_m_d_H_i_s");
$logsDirectory = \Drupal::service('file_system')
->realpath($folder . "://logs/");
//Retrieve all the files in the folder.
$logs = glob($logsDirectory . "/*.log");
$archiveName = $date . $format;
$archive_path = \Drupal::service('file_system')
->saveData('', 'temporary://' . $archiveName);
$archive = \Drupal::service('plugin.manager.archiver')
->getInstance(['filepath' => $archive_path]);
foreach ($logs as $log) {
$archive->add($log);
}
$response = new BinaryFileResponse($archive_path);
$response->headers->set('Content-type', $this->getContentTypes($format));
$response->headers->set('Content-Disposition', 'attachment;filename="' . $archive_path . '"');
$form_state->setResponse($response);
}
Everything is going fine, I managed to achieve a button in this way that, when pressed, downloads the archive with all the log files inside.
The problem is that inside of this zip all the files are inside their absolute path, in this way:
This is because in the ArchiveInterface Class the add method only accepts one parameter, $file_path
, and it is not supported to add a second parameter to specify the name of the files.
How could I solve this problem, being able of adding inside the archive only the files and not all the subfolders?