diff --git a/README.md b/README.md index 1813b03..58fd9d6 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,14 @@ echo $config->get("database.port"); // 6612 echo $config->get("database.password"); // super-secret-passw0rd ``` +## Selecting an environment + +Project configuration defaults to production behaviour. Use exactly one environment file: `config.dev.ini` or `config.development.ini`, `config.stag.ini` or `config.staging.ini`, or `config.prod.ini` or `config.production.ini`. Multiple environment files, including aliases for the same environment, throw `EnvironmentConfigurationException` before parsing. + +`isProduction()` returns false only in development. Staging keeps production behaviour and can be identified with `isStaging()`. An explicit `app.production=false` also selects development when no environment file is present. Explicit flags and the `app_production` environment variable must agree with a selected environment file. + +See the [environment selection documentation](https://github.com/phpgt/Config/wiki/Automatically-loading-config#selecting-an-environment) for load order, boolean values and deployment guidance. + ## Example usage - generating configuration files: Sometimes it's useful to generate config files on-the-fly, such as from Continuous Integration scripts. Below shows a quick example of how to generate a `config.deploy.ini` file with a few key-values that will override the default. diff --git a/phpunit.xml b/phpunit.xml index aacb03a..d5d1153 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -22,6 +22,9 @@ ./test/phpunit/ + + ./test/integration/ + diff --git a/src/Config.php b/src/Config.php index 1665d1a..8b1a998 100644 --- a/src/Config.php +++ b/src/Config.php @@ -5,7 +5,11 @@ use GT\TypeSafeGetter\TypeSafeGetter; class Config implements TypeSafeGetter { - use NullableTypeSafeGetter; + use NullableTypeSafeGetter { + getBool as private getGenericBool; + } + + private ?Environment $environment = null; /** @var ConfigSection[] */ protected array $sectionList = []; @@ -29,8 +33,65 @@ public function getSection(string $sectionName):?ConfigSection { return $this->sectionList[$sectionName] ?? null; } + /** @SuppressWarnings("PHPMD.BooleanGetMethodName") */ + public function getBool(string $name):?bool { + if($name === "app.production") { + return $this->isProduction(); + } + + return $this->getGenericBool($name); + } + public function isProduction():bool { - return $this->getBool("app.production") ?? false; + $production = $this->isProductionConfigured(); + if($this->environment === null) { + return $production ?? true; + } + + $expected = $this->environment !== Environment::DEVELOPMENT; + if($production !== null && $production !== $expected) { + throw new EnvironmentConfigurationException( + "app.production contradicts the selected " + . $this->environment->value . " environment." + ); + } + + return $expected; + } + + public function isDevelopment():bool { + return !$this->isProduction(); + } + + public function isStaging():bool { + $this->isProduction(); + return $this->environment === Environment::STAGING; + } + + public function withEnvironment(Environment $environment):self { + $clone = clone $this; + $clone->environment = $environment; + $clone->isProduction(); + return $clone; + } + + private function isProductionConfigured():?bool { + $value = getenv("app_production"); + if($value === false) { + $value = $this->getSectionValue("app.production"); + } + + if($value === null) { + return null; + } + + return match(strtolower(trim($value))) { + "1", "true", "yes", "on" => true, + "0", "false", "no", "off" => false, + default => throw new EnvironmentConfigurationException( + "app.production must be a valid boolean." + ), + }; } protected function getSectionValue(string $name):?string { @@ -81,7 +142,11 @@ public function withMerge(Config $configToOverride): self { } } - return new self(...array_values($mergedSectionList)); + $merged = clone $this; + $merged->sectionList = $mergedSectionList; + $merged->environment ??= $configToOverride->environment; + $merged->isProduction(); + return $merged; } /** @@ -96,5 +161,6 @@ public function merge(Config $configToOverride):void { ); $new = $this->withMerge($configToOverride); $this->sectionList = $new->sectionList; + $this->environment = $new->environment; } } diff --git a/src/ConfigFactory.php b/src/ConfigFactory.php index c8be0a7..bcf1180 100644 --- a/src/ConfigFactory.php +++ b/src/ConfigFactory.php @@ -5,60 +5,41 @@ class ConfigFactory { const EXTENSION = "ini"; const FILE_DEFAULT = "default"; const FILE_OVERRIDE_ORDER = [ - "dev", - "deploy", - "production", + "dev", "development", "deploy", "stag", "staging", "prod", "production", + ]; + const ENVIRONMENT_FILES = [ + "dev" => Environment::DEVELOPMENT, + "development" => Environment::DEVELOPMENT, + "stag" => Environment::STAGING, + "staging" => Environment::STAGING, + "prod" => Environment::PRODUCTION, + "production" => Environment::PRODUCTION, ]; public static function createForProject( string $projectRoot, ?string $defaultConfigPathName = null ):Config { - $order = array_merge( - [self::FILE_DEFAULT, ""], - self::FILE_OVERRIDE_ORDER - ); - - $previousConfig = null; - - if(!is_null($defaultConfigPathName)) { - $previousConfig = ConfigFactory::createFromPathName( - $defaultConfigPathName - ); - } + $environmentFiles = self::findEnvironmentFiles($projectRoot); + $order = array_merge([self::FILE_DEFAULT, ""], self::FILE_OVERRIDE_ORDER); + $config = $defaultConfigPathName === null + ? new Config() + : self::createFromPathName($defaultConfigPathName) ?? new Config(); foreach($order as $file) { - $fileName = "config"; - $fileName .= "."; - - if(!empty($file)) { - $fileName .= $file; - $fileName .= "."; - } - - $fileName .= self::EXTENSION; - $config = self::createFromPathName( - implode(DIRECTORY_SEPARATOR, [ - $projectRoot, - $fileName, - ]) - ); - if(is_null($config)) { - continue; - } - - if($previousConfig) { - $config = $config->withMerge($previousConfig); - } - - if($file === "production") { - $config = self::withProductionFlag($config); + $path = $projectRoot . DIRECTORY_SEPARATOR . self::fileName($file); + $override = self::createFromPathName($path); + if($override !== null) { + $config = $override->withMerge($config); } + } - $previousConfig = $config; + foreach($environmentFiles as $environment) { + return $config->withEnvironment($environment); } - return $config ?? $previousConfig; + $config->isProduction(); + return $config; } public static function createFromPathName(string $pathName):?Config { @@ -70,16 +51,27 @@ public static function createFromPathName(string $pathName):?Config { return $parser->parse(); } - protected static function withProductionFlag(Config $config):Config { - $appSection = $config->getSection("app"); - if($appSection && $appSection->contains("production")) { - return $config; + /** @return array */ + private static function findEnvironmentFiles(string $projectRoot):array { + $found = []; + foreach(self::ENVIRONMENT_FILES as $file => $environment) { + $fileName = self::fileName($file); + if(is_file($projectRoot . DIRECTORY_SEPARATOR . $fileName)) { + $found[$fileName] = $environment; + } + } + + if(count($found) > 1) { + throw new EnvironmentConfigurationException( + "Only one environment configuration file is allowed: " + . implode(", ", array_keys($found)) . "." + ); } - return $config->withMerge(new Config( - new ConfigSection("app", [ - "production" => "true", - ]) - )); + return $found; + } + + private static function fileName(string $suffix):string { + return "config" . ($suffix === "" ? "" : ".$suffix") . "." . self::EXTENSION; } } diff --git a/src/Environment.php b/src/Environment.php new file mode 100644 index 0000000..92dd77f --- /dev/null +++ b/src/Environment.php @@ -0,0 +1,8 @@ + $sectionData) { $configSectionList []= new ConfigSection( diff --git a/test/integration/ConfigFactoryTest.php b/test/integration/ConfigFactoryTest.php new file mode 100644 index 0000000..241ac19 --- /dev/null +++ b/test/integration/ConfigFactoryTest.php @@ -0,0 +1,130 @@ +directory = sys_get_temp_dir() . "/config-environment-" . uniqid(); + mkdir($this->directory); + $this->previousProduction = getenv("app_production"); + putenv("app_production"); + } + + protected function tearDown():void { + putenv($this->previousProduction === false ? "app_production" : "app_production=$this->previousProduction"); + foreach(glob("$this->directory/*") as $file) { + unlink($file); + } + rmdir($this->directory); + } + + #[DataProvider("environments")] + public function testCreateForProject_selectsEnvironmentAndPreservesOverrides(string $suffix, bool $production, bool $staging):void { + file_put_contents("$this->directory/config.default.ini", "[database]\nhost=default\npassword=secret-default\n"); + file_put_contents("$this->directory/config.ini", "[database]\nhost=base\n"); + file_put_contents("$this->directory/config.$suffix.ini", "[database]\nhost=environment\n"); + + $sut = ConfigFactory::createForProject($this->directory); + + self::assertSame($production, $sut->isProduction()); + self::assertSame(!$production, $sut->isDevelopment()); + self::assertSame($staging, $sut->isStaging()); + self::assertSame($production, $sut->getBool("app.production")); + self::assertSame("environment", $sut->get("database.host")); + self::assertSame("secret-default", $sut->get("database.password")); + } + + public static function environments():iterable { + yield ["dev", false, false]; + yield ["development", false, false]; + yield ["stag", true, true]; + yield ["staging", true, true]; + yield ["prod", true, false]; + yield ["production", true, false]; + } + + #[DataProvider("conflictingFiles")] + public function testCreateForProject_rejectsEveryPairBeforeParsing(string $first, string $second):void { + file_put_contents("$this->directory/config.$first.ini", "invalid INI [ secret-value"); + file_put_contents("$this->directory/config.$second.ini", "invalid INI [ another-secret"); + + $this->expectException(EnvironmentConfigurationException::class); + $this->expectExceptionMessageMatches( + "/" . preg_quote("config.$first.ini", "/") . ".*" + . preg_quote("config.$second.ini", "/") . "/" + ); + ConfigFactory::createForProject($this->directory); + } + + public static function conflictingFiles():iterable { + $names = ["dev", "development", "stag", "staging", "prod", "production"]; + foreach($names as $index => $first) { + foreach(array_slice($names, $index + 1) as $second) { + yield "$first and $second" => [$first, $second]; + } + } + } + + #[DataProvider("flagConflicts")] + public function testCreateForProject_rejectsContradictoryFlags(string $suffix, string $flag):void { + file_put_contents("$this->directory/config.$suffix.ini", "[app]\nproduction=$flag\n"); + + $this->expectException(EnvironmentConfigurationException::class); + $this->expectExceptionMessage("contradicts"); + ConfigFactory::createForProject($this->directory); + } + + public static function flagConflicts():iterable { + yield ["development", "true"]; + yield ["staging", "false"]; + yield ["production", "false"]; + } + + public function testCreateForProject_environmentVariableCannotDisableStagingSafeguards():void { + file_put_contents("$this->directory/config.staging.ini", ""); + putenv("app_production=false"); + + $this->expectException(EnvironmentConfigurationException::class); + ConfigFactory::createForProject($this->directory); + } + + public function testCreateForProject_externalDefaultsRemainFallbackValues():void { + file_put_contents("$this->directory/framework.ini", "[app]\nproduction=false\n[database]\nhost=framework\nport=3306\n"); + file_put_contents("$this->directory/config.ini", "[database]\nhost=project\n"); + + $sut = ConfigFactory::createForProject($this->directory, "$this->directory/framework.ini"); + + self::assertTrue($sut->isDevelopment()); + self::assertSame("project", $sut->get("database.host")); + self::assertSame(3306, $sut->getInt("database.port")); + } + + public function testCreateForProject_missingExternalDefaultsStillUsesProduction():void { + $sut = ConfigFactory::createForProject($this->directory, "$this->directory/missing.ini"); + self::assertTrue($sut->isProduction()); + } + + public function testCreateForProject_noFilesDefaultsToProduction():void { + $sut = ConfigFactory::createForProject($this->directory); + self::assertTrue($sut->isProduction()); + self::assertFalse($sut->isDevelopment()); + self::assertFalse($sut->isStaging()); + } + + public function testCreateForProject_explicitFalseSelectsDevelopmentWithDeployOverrides():void { + file_put_contents("$this->directory/config.ini", "[app]\nproduction=false\n[database]\nhost=base\n"); + file_put_contents("$this->directory/config.deploy.ini", "[database]\nhost=deployed\n"); + + $sut = ConfigFactory::createForProject($this->directory); + self::assertTrue($sut->isDevelopment()); + self::assertFalse($sut->getBool("app.production")); + self::assertSame("deployed", $sut->get("database.host")); + } +} diff --git a/test/phpunit/ConfigFactoryTest.php b/test/phpunit/ConfigFactoryTest.php index ff6b803..fbab415 100644 --- a/test/phpunit/ConfigFactoryTest.php +++ b/test/phpunit/ConfigFactoryTest.php @@ -14,10 +14,6 @@ public function testCreateForProject():void { $this->tmp, "config.default.ini", ]); - $filePathDev = implode(DIRECTORY_SEPARATOR, [ - $this->tmp, - "config.dev.ini", - ]); $filePathProduction = implode(DIRECTORY_SEPARATOR, [ $this->tmp, "config.production.ini", @@ -25,12 +21,11 @@ public function testCreateForProject():void { file_put_contents($filePathDefault, Helper::INI_DEFAULT); file_put_contents($filePath, Helper::INI_SIMPLE); - file_put_contents($filePathDev, Helper::INI_OVERRIDE_DEV); file_put_contents($filePathProduction, Helper::INI_OVERRIDE_PROD); $config = ConfigFactory::createForProject($this->tmp); self::assertEquals("ExampleApp", $config->get("app.namespace")); - self::assertEquals("dev789override", $config->get("block1.value.nested")); + self::assertEquals("789", $config->get("block1.value.nested")); self::assertEquals("this appears by default", $config->get("block1.value.existsByDefault")); self::assertEquals("my.production.database", $config->get("database.host")); self::assertEquals("example", $config->get("database.schema")); @@ -102,7 +97,7 @@ public function testCreateForProjectProductionFileDoesNotOverrideExplicitFlag(): ])); file_put_contents($filePathProduction, Helper::INI_OVERRIDE_PROD); - $config = ConfigFactory::createForProject($this->tmp); - self::assertFalse($config->isProduction()); + $this->expectException(\GT\Config\EnvironmentConfigurationException::class); + ConfigFactory::createForProject($this->tmp); } } diff --git a/test/phpunit/ConfigTest.php b/test/phpunit/ConfigTest.php index f3c72f7..987cda9 100644 --- a/test/phpunit/ConfigTest.php +++ b/test/phpunit/ConfigTest.php @@ -74,10 +74,10 @@ public function testTypeSafeGetter() { self::assertNull($sut->getFloat("nothing-here")); } - public function testIsProductionDefaultsToFalse():void { + public function testIsProductionDefaultsToTrue():void { putenv("app_production"); $config = new Config(); - self::assertFalse($config->isProduction()); + self::assertTrue($config->isProduction()); } public function testIsProductionUsesAppProductionValue():void { @@ -94,6 +94,71 @@ public function testIsProductionUsesAppProductionValue():void { putenv("app_production"); } + #[\PHPUnit\Framework\Attributes\DataProvider("productionFlags")] + public function testIsProduction_parsesEnvironmentBooleans(string $value, bool $expected):void { + $previous = getenv("app_production"); + putenv("app_production=$value"); + $sut = new Config(); + + try { + self::assertSame($expected, $sut->isProduction()); + self::assertSame($expected, $sut->getBool("app.production")); + self::assertSame(!$expected, $sut->isDevelopment()); + self::assertFalse($sut->isStaging()); + } + finally { + putenv($previous === false ? "app_production" : "app_production=$previous"); + } + } + + public static function productionFlags():iterable { + foreach(["true", "1", "yes", "on", " TRUE "] as $value) { + yield [$value, true]; + } + foreach(["false", "0", "no", "off", " FALSE "] as $value) { + yield [$value, false]; + } + } + + public function testIsProduction_rejectsAnInvalidFlagWithoutDisclosingItsValue():void { + $previous = getenv("app_production"); + putenv("app_production=secret-invalid-value"); + $sut = new Config(); + + try { + $sut->isProduction(); + self::fail("Expected an invalid environment exception"); + } + catch(\GT\Config\EnvironmentConfigurationException $exception) { + self::assertStringContainsString("app.production", $exception->getMessage()); + self::assertStringNotContainsString("secret-invalid-value", $exception->getMessage()); + } + finally { + putenv($previous === false ? "app_production" : "app_production=$previous"); + } + } + + public function testWithMerge_preservesStagingWithoutMutatingTheOriginal():void { + $sut = (new Config())->withEnvironment(\GT\Config\Environment::STAGING); + $merged = $sut->withMerge(new Config(new ConfigSection("database", ["host" => "staging-db"]))); + + self::assertNotSame($sut, $merged); + self::assertNull($sut->get("database.host")); + self::assertTrue($sut->isStaging()); + self::assertTrue($merged->isStaging()); + self::assertTrue($merged->isProduction()); + self::assertSame("staging-db", $merged->get("database.host")); + } + + public function testWithMerge_preservesTheFallbackEnvironment():void { + $sut = new Config(new ConfigSection("database", ["host" => "custom"])); + $merged = $sut->withMerge((new Config())->withEnvironment(\GT\Config\Environment::DEVELOPMENT)); + + self::assertTrue($sut->isProduction()); + self::assertTrue($merged->isDevelopment()); + self::assertSame("custom", $merged->get("database.host")); + } + public function testWithMergeReturnsNewAndDoesNotMutateOriginal():void { $original = new Config( new ConfigSection("app", [