From 001f1761e7904927ac16297711e55b9daab0c3f5 Mon Sep 17 00:00:00 2001 From: Stein Magne Bjorklund <steinmb@smbjorklund.com> Date: Mon, 20 Sep 2021 19:39:55 +0200 Subject: [PATCH] Wrap global config in a config class - Inject this into the needed classes and get away from globals. --- classes/Configuration.php | 37 ++++++++++++++++++++++++++++++++++ index.php | 5 ++++- tests/ConfigurationTest.php | 40 +++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 classes/Configuration.php create mode 100644 tests/ConfigurationTest.php diff --git a/classes/Configuration.php b/classes/Configuration.php new file mode 100644 index 00000000..a2479411 --- /dev/null +++ b/classes/Configuration.php @@ -0,0 +1,37 @@ +<?php declare(strict_types=1); + +namespace uib\ub\loadspeakr; + +final class Configuration +{ + private array $configs; + + /** + * @throws \Exception + */ + public function __construct(array $conf) + { + if (count($conf) === 0) { + throw new \Exception( + 'Configuration empty. Giving up.' + ); + } + + $this->configs['conf'] = $conf; + } + + public function getConfigValue(string $type, string $key) + { + if (!isset($this->configs[$type][$key])) { + return ''; + } + + return $this->configs[$type][$key]; + } + + public function debugMode(): bool + { + return $this->configs['conf']['debug']; + } + +} diff --git a/index.php b/index.php index abc16855..be0eace4 100644 --- a/index.php +++ b/index.php @@ -13,8 +13,11 @@ const LOADSPEAKR_ROOT = __DIR__; require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/common.inc.php'; +global $conf; +$configuration = new uib\ub\loadspeakr\Configuration($conf); + if (isset($_GET['q']) && $_GET['q'] === 'import') { - $imp = new Importer(); + $imp = new Importer($configuration); $imp->run(); exit(0); } diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php new file mode 100644 index 00000000..e827858e --- /dev/null +++ b/tests/ConfigurationTest.php @@ -0,0 +1,40 @@ +<?php declare(strict_types=1); + +use PHPUnit\Framework\TestCase; +use uib\ub\loadspeakr\Configuration; + +final class ConfigurationTest extends TestCase +{ + public Configuration $configuration; + + public function setUp(): void + { + $conf = [ + 'foo' => 'bar', + 'debug' => true, + 'multiple' => ['one', 'two'] + ]; + + $this->configuration = new Configuration($conf); + } + + + /** + * @covers \uib\ub\loadspeakr\Configuration::getConfigValue + */ + public function testGetConfigValue(): void + { + self::assertSame('bar', $this->configuration->getConfigValue('conf', 'foo')); + self::assertCount(2, $this->configuration->getConfigValue('conf', 'multiple'), + 'Unable to get settings storing multiple values.' + ); + } + + /** + * @covers \uib\ub\loadspeakr\Configuration::debugMode + */ + public function testDebugMode(): void + { + self::assertTrue($this->configuration->debugMode()); + } +} -- GitLab