TempFileAdapter.php in Backup and Migrate 5.0.x
File
src/Core/File/TempFileAdapter.php
View source
<?php
namespace Drupal\backup_migrate\Core\File;
use Drupal\backup_migrate\Core\Exception\BackupMigrateException;
class TempFileAdapter implements TempFileAdapterInterface {
protected $dir;
protected $prefix;
protected $tempfiles;
public function __construct($dir, $prefix = 'bam') {
if (substr($dir, -1) !== '/') {
$dir .= '/';
}
$this->dir = $dir;
$this->prefix = $prefix;
$this->tempfiles = [];
}
public function __destruct() {
$this
->deleteAllTempFiles();
}
public function createTempFile($ext = '') {
$ext = $ext ? '.' . $ext : '';
$try = 5;
do {
$out = $this->dir . $this->prefix . mt_rand() . $ext;
$fp = @fopen($out, 'x');
} while (!$fp && $try-- > 0);
if ($fp) {
fclose($fp);
}
else {
throw new \Exception('Could not create a temporary file to write to.');
}
$this->tempfiles[] = $out;
return $out;
}
public function deleteTempFile($filename) {
if (in_array($filename, $this->tempfiles)) {
if (file_exists($filename)) {
if (is_writable($filename)) {
unlink($filename);
}
else {
throw new BackupMigrateException('Could not delete the temp file: %file because it is not writable', [
'%file' => $filename,
]);
}
}
$this->tempfiles = array_diff($this->tempfiles, [
$filename,
]);
return;
}
throw new BackupMigrateException('Attempting to delete a temp file not managed by this codebase: %file', [
'%file' => $filename,
]);
}
public function deleteAllTempFiles() {
foreach ($this->tempfiles as $file) {
$this
->deleteTempFile($file);
}
}
}