From 49c621fbeb17d51b2f1370d39cc20e2fe1d470de Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 12 Mar 2024 16:18:08 +0100 Subject: [PATCH] Introduce trait `ipl\Sql\Test\Databases` --- src/Test/Databases.php | 129 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 src/Test/Databases.php diff --git a/src/Test/Databases.php b/src/Test/Databases.php new file mode 100644 index 0000000..fb2da0c --- /dev/null +++ b/src/Test/Databases.php @@ -0,0 +1,129 @@ + + */ + public function databases(): array + { + $supportedAdapters = ['mssql', 'mysql', 'oracle', 'pgsql', 'sqlite']; + + $connections = []; + foreach ($supportedAdapters as $driver) { + if (isset($_SERVER[strtoupper($driver) . '_TESTDB'])) { + $connections[$driver] = [$this->createConnection($driver)]; + } + } + + return $connections; + } + + /** + * Get the value of an environment variable + * + * @param string $name + * + * @return string + * + * @throws RuntimeException if the environment variable is not set + */ + private function getEnvVariable(string $name): string + { + $value = getenv($name); + if ($value === false) { + throw new RuntimeException("Environment variable $name is not set"); + } + + return $value; + } + + /** + * Create a database connection + * + * @param string $driver + * + * @return Connection + */ + private function createConnection(string $driver): Connection + { + return new Connection([ + 'db' => $driver, + 'host' => $this->getEnvVariable(strtoupper($driver) . '_TESTDB_HOST'), + 'port' => $this->getEnvVariable(strtoupper($driver) . '_TESTDB_PORT'), + 'username' => $this->getEnvVariable(strtoupper($driver) . '_TESTDB_USER'), + 'password' => $this->getEnvVariable(strtoupper($driver) . '_TESTDB_PASSWORD'), + 'dbname' => $this->getEnvVariable(strtoupper($driver) . '_TESTDB'), + ]); + } + + public function setUp(): void + { + if (method_exists($this, 'dataName') && method_exists($this, 'getProvidedData')) { + // A small performance improvement. Though, it relies on internal methods, hence the check. + $this->createSchema($this->getProvidedData()[0], $this->dataName()); + } else { + $this->createSchema($this->createConnection('mysql'), 'mysql'); + $this->createSchema($this->createConnection('pgsql'), 'pgsql'); + } + } + + public function tearDown(): void + { + if (method_exists($this, 'dataName') && method_exists($this, 'getProvidedData')) { + // A small performance improvement. Though, it relies on internal methods, hence the check. + $this->dropSchema($this->getProvidedData()[0], $this->dataName()); + } else { + $this->dropSchema($this->createConnection('mysql'), 'mysql'); + $this->dropSchema($this->createConnection('pgsql'), 'pgsql'); + } + } +}