dbmanager/src/Service/BackupService.php
2021-12-16 01:40:55 +01:00

46 lines
1.2 KiB
PHP

<?php
namespace App\Service;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\InputStream;
use Symfony\Component\Process\Process;
class BackupService
{
public function __construct(private DatabaseCredentials $credentials)
{
}
public function backup(string $db, ?string $fileName = null): string
{
if (!$fileName) {
$fileName = sprintf('%s_backup.sql', $db);
}
$filesystem = new Filesystem();
$process = new Process([
'mysqldump',
'-B', $db,
'-u', $this->credentials->getUser(),
]);
$process->setEnv(['MYSQL_PWD' => $this->credentials->getPassword()]);
$process->run();
$filesystem->dumpFile($fileName, $process->getOutput());
return $fileName;
}
public function restore(string $db, string $fileName): void
{
$process = new Process([
'mysql',
'-u', $this->credentials->getUser(),
$db,
]);
$process->setEnv(['MYSQL_PWD' => $this->credentials->getPassword()]);
$process->setInput(file_get_contents($fileName));
$process->run();
}
}