1 <?php declare(strict_types=1);
3 namespace Cli\Services;
6 use Symfony\Component\Process\Exception\ProcessTimedOutException;
10 public function __construct(
11 protected string $host,
12 protected string $user,
13 protected string $password,
14 protected string $database,
15 protected int $port = 3306
22 public function ensureOptionsSet(): void
24 $options = ['host', 'user', 'password', 'database'];
25 foreach ($options as $option) {
26 if (!$this->$option) {
27 throw new Exception("Could not find a valid value for the \"{$option}\" database option.");
32 protected function createOptionsFile(): string
34 $path = tempnam(sys_get_temp_dir(), 'bs-cli-mysql-opts');
35 $contents = "[client]\nuser={$this->user}\nhost={$this->host}\nport={$this->port}\npassword={$this->password}\nprotocol=TCP";
36 file_put_contents($path, $contents);
41 protected function getProgramRunnerInstance(): ProgramRunner
43 return (new ProgramRunner(['mariadb', 'mysql'], '/usr/bin/mysql'));
46 public function testConnection(): bool
48 $optionsFile = $this->createOptionsFile();
51 $stdErr = $this->getProgramRunnerInstance()
53 ->withIdleTimeout(300)
54 ->runCapturingStdErr([
55 "--defaults-file={$optionsFile}",
60 } catch (Exception $exception) {
68 public function importSqlFile(string $sqlFilePath): void
70 $optionsFile = $this->createOptionsFile();
73 $output = $this->getProgramRunnerInstance()
75 ->withIdleTimeout(300)
76 ->runCapturingStdErr([
77 "--defaults-file={$optionsFile}",
79 '-e', "source {$sqlFilePath}"
82 } catch (Exception $exception) {
88 throw new Exception("Failed mysql file import with errors:\n{$output}");
92 public function dropTablesSql(): string
95 SET FOREIGN_KEY_CHECKS = 0;
96 SET GROUP_CONCAT_MAX_LEN=32768;
98 SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
99 FROM information_schema.tables
100 WHERE table_schema = (SELECT DATABASE());
101 SELECT IFNULL(@tables,'dummy') INTO @tables;
103 SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
104 PREPARE stmt FROM @tables;
106 DEALLOCATE PREPARE stmt;
107 SET FOREIGN_KEY_CHECKS = 1;
111 public function runDumpToFile(string $filePath): string
113 $file = fopen($filePath, 'w');
117 $optionsFile = $this->createOptionsFile();
120 (new ProgramRunner(['mariadb-dump', 'mysqldump'], '/usr/bin/mysqldump'))
122 ->withIdleTimeout(300)
123 ->withAdditionalPathLocation('C:\xampp\mysql\bin')
124 ->runWithoutOutputCallbacks([
125 "--defaults-file={$optionsFile}",
126 '--single-transaction',
129 ], function ($data) use (&$file, &$hasOutput) {
130 fwrite($file, $data);
132 }, function ($error) use (&$errors, &$warnings) {
133 $lines = explode("\n", $error);
134 foreach ($lines as $line) {
135 if (str_starts_with(strtolower($line), 'warning: ')) {
137 } else if (!empty(trim($line))) {
138 $errors .= $line . "\n";
142 unlink($optionsFile);
143 } catch (\Exception $exception) {
145 unlink($optionsFile);
146 if ($exception instanceof ProcessTimedOutException) {
148 throw new Exception("mysqldump operation timed-out.\nNo data has been received so the connection to your database may have failed.");
150 throw new Exception("mysqldump operation timed-out after data was received.");
153 throw new Exception($exception->getMessage());
159 throw new Exception("Failed mysqldump with errors:\n" . $errors);
165 public static function fromEnvOptions(array $env): static
167 $host = ($env['DB_HOST'] ?? '');
168 $username = ($env['DB_USERNAME'] ?? '');
169 $password = ($env['DB_PASSWORD'] ?? '');
170 $database = ($env['DB_DATABASE'] ?? '');
171 $port = intval($env['DB_PORT'] ?? 3306);
173 return new static($host, $username, $password, $database, $port);