From 3b911bcabd70d1c3c7b7c71fdb09a6b4daec753d Mon Sep 17 00:00:00 2001 From: jamesread Date: Mon, 28 Aug 2023 15:11:11 +0000 Subject: [PATCH] ConfigFile class --- src/main/php/libAllure/ConfigFile.php | 82 +++++++++++++++++++++++++++ src/test/php/ConfigFileTest.php | 52 +++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 src/main/php/libAllure/ConfigFile.php create mode 100644 src/test/php/ConfigFileTest.php diff --git a/src/main/php/libAllure/ConfigFile.php b/src/main/php/libAllure/ConfigFile.php new file mode 100644 index 0000000..3f5e0d6 --- /dev/null +++ b/src/main/php/libAllure/ConfigFile.php @@ -0,0 +1,82 @@ +keys = []; + + if ($useDefaultKeys) { + $this->keys['DB_NAME'] = 'unknown'; + $this->keys['DB_HOST'] = 'localhost'; + $this->keys['DB_USER'] = 'user'; + $this->keys['DB_PASS'] = 'password'; + $this->keys['TIMEZONE'] = 'Europe/London'; + } + + if (is_array($additionalKeys)) { + $this->keys = array_merge($this->keys, $additionalKeys); + } + } + + public function tryLoad(array $possiblePaths) + { + $foundAConfig = false; + + foreach ($possiblePaths as $path) { + if (file_exists($path . $this->filename)) { + $foundAConfig = true; + $this->load($path . $this->filename); + } + } + + if (!$foundAConfig) { + $this->createConfigFile($possiblePaths[0]); + } + } + + private function createConfigFile($path) + { + if (!is_writable($path)) { + throw new \Exception('Could not save a default config file as the path is not writable: ' . $path); + } + + $content = ''; + + foreach ($this->keys as $key => $val) { + $content .= $key . '=' . $val . "\n"; + } + + file_put_contents($path . $this->filename, $content); + } + + private function load($fullpath) + { + $this->keys = parse_ini_file($fullpath, false); + } + + public function getAll(): array + { + return $this->keys; + } + + public function get($k): ?string + { + if (isset($this->keys[$k])) { + return $this->keys[$k]; + } + + return null; + } + + public function getDsn($type = 'mysql'): string + { + return $type . ':dbname=' . $this->get('DB_NAME'); + } +} diff --git a/src/test/php/ConfigFileTest.php b/src/test/php/ConfigFileTest.php new file mode 100644 index 0000000..37cf945 --- /dev/null +++ b/src/test/php/ConfigFileTest.php @@ -0,0 +1,52 @@ +assertEquals('localhost', $cfg->get('DB_HOST')); + } + + public function testAdditionalKeys() + { + $cfg = new ConfigFile([ + 'blat' => 'hi', + ]); + + $this->assertEquals('hi', $cfg->get('blat')); + $this->assertEquals('localhost', $cfg->get('DB_HOST')); + } + + public function testNoAdditionalKeys() + { + $cfg = new ConfigFile(null, false); + + $this->assertSame(null, $cfg->get('DB_HOST')); + } + + public function testLoad() + { + $cfg = new ConfigFile(); + $cfg->tryLoad([ + '/tmp/libAllure/', + ]); + + $this->assertSame('localhost', $cfg->get('DB_HOST')); + } +}