From 5f353cb511b07e9c1ebea5432532ba483ccec064 Mon Sep 17 00:00:00 2001 From: Sean Molenaar Date: Fri, 12 Jul 2024 22:01:04 +0200 Subject: [PATCH] General: Load ENV as configuration --- src/Lunr/Core/Configuration.php | 23 +++++ .../ConfigurationLoadEnvironmentTest.php | 88 +++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 src/Lunr/Core/Tests/ConfigurationLoadEnvironmentTest.php diff --git a/src/Lunr/Core/Configuration.php b/src/Lunr/Core/Configuration.php index fb16209..e87fe75 100644 --- a/src/Lunr/Core/Configuration.php +++ b/src/Lunr/Core/Configuration.php @@ -143,6 +143,29 @@ public function load_file(string $identifier): void $this->size_invalid = TRUE; } + /** + * Load environment variables as configuration. + * + * @return void + */ + public function load_environment(): void + { + $config = $this->config; + + foreach ($_ENV as $key => $value) + { + $config[strtolower($key)] = $value; + } + + if (!empty($config)) + { + $config = $this->convert_array_to_class($config); + } + + $this->config = $config; + $this->size_invalid = TRUE; + } + /** * Convert an input array recursively into a Configuration class hierarchy. * diff --git a/src/Lunr/Core/Tests/ConfigurationLoadEnvironmentTest.php b/src/Lunr/Core/Tests/ConfigurationLoadEnvironmentTest.php new file mode 100644 index 0000000..b99479a --- /dev/null +++ b/src/Lunr/Core/Tests/ConfigurationLoadEnvironmentTest.php @@ -0,0 +1,88 @@ +setUpArray($this->construct_test_array()); + } + + /** + * Test loading the environment correctly. + */ + public function testLoadEnvironment(): void + { + $_ENV = []; + + $_ENV['LOAD_ONE'] = 'Value'; + $_ENV['LOAD_TWO'] = 'String'; + + $this->class->load_environment(); + + $this->config['load_one'] = 'Value'; + $this->config['load_two'] = 'String'; + + $this->assertEquals($this->config, $this->class->toArray()); + + unset($_ENV['LOAD_ONE']); + unset($_ENV['LOAD_TWO']); + } + + /** + * Test loading a correct config file. + */ + public function testLoadFileOverwritesValues(): void + { + $_ENV = []; + + $_ENV['TEST1'] = 'Test'; + + $this->class->load_environment(); + + $config = []; + $config['test1'] = 'Test'; + $config['test2'] = $this->config['test2']; + + $this->assertEquals($config, $this->class->toArray()); + + unset($_ENV['TEST1']); + } + + /** + * Test that loading a file invalidates the cached size value. + */ + public function testLoadFileInvalidatesSize(): void + { + $property = $this->reflection->getProperty('size_invalid'); + $property->setAccessible(TRUE); + + $this->assertFalse($property->getValue($this->class)); + + $this->class->load_file('correct'); + + $this->assertTrue($property->getValue($this->class)); + } + +} + +?>