1 <?php declare(strict_types=1);
3 namespace Cli\Services;
9 public function __construct(
10 protected string $host,
11 protected string $user,
12 protected string $password,
13 protected string $database,
14 protected int $port = 3306
21 public function ensureOptionsSet(): void
23 $options = ['host', 'user', 'password', 'database'];
24 foreach ($options as $option) {
25 if (!$this->$option) {
26 throw new Exception("Could not find a valid value for the \"{$option}\" database option.");
31 public function testConnection(): bool
33 $output = (new ProgramRunner('mysql', '/usr/bin/mysql'))
36 ->runCapturingStdErr([
40 '-p' . $this->password,
48 public function importSqlFile(string $sqlFilePath): void
50 $output = (new ProgramRunner('mysql', '/usr/bin/mysql'))
53 ->runCapturingStdErr([
57 '-p' . $this->password,
63 throw new Exception("Failed mysql file import with errors:\n" . $output);
67 public function runDumpToFile(string $filePath): void
69 $file = fopen($filePath, 'w');
74 (new ProgramRunner('mysqldump', '/usr/bin/mysqldump'))
77 ->runWithoutOutputCallbacks([
81 '-p' . $this->password,
82 '--single-transaction',
85 ], function ($data) use (&$file, &$hasOutput) {
88 }, function ($error) use (&$errors) {
89 if (!str_contains($error, '[Warning] ')) {
90 $errors .= $error . "\n";
93 } catch (\Exception $exception) {
95 if ($exception instanceof ProcessTimedOutException) {
97 throw new Exception("mysqldump operation timed-out.\nNo data has been received so the connection to your database may have failed.");
99 throw new Exception("mysqldump operation timed-out after data was received.");
102 throw new Exception($exception->getMessage());
108 throw new Exception("Failed mysqldump with errors:\n" . $errors);
112 public static function fromEnvOptions(array $env): static
114 $host = ($env['DB_HOST'] ?? '');
115 $username = ($env['DB_USERNAME'] ?? '');
116 $password = ($env['DB_PASSWORD'] ?? '');
117 $database = ($env['DB_DATABASE'] ?? '');
118 $port = intval($env['DB_PORT'] ?? 3306);
120 return new static($host, $username, $password, $database, $port);