Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
./test/phpunit/
</directory>
</testsuite>
<testsuite name="integration">
<directory>./test/integration/</directory>
</testsuite>
</testsuites>

<logging />
Expand Down
72 changes: 69 additions & 3 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand All @@ -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 {
Expand Down Expand Up @@ -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;
}

/**
Expand All @@ -96,5 +161,6 @@ public function merge(Config $configToOverride):void {
);
$new = $this->withMerge($configToOverride);
$this->sectionList = $new->sectionList;
$this->environment = $new->environment;
}
}
94 changes: 43 additions & 51 deletions src/ConfigFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<string, Environment> */
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;
}
}
8 changes: 8 additions & 0 deletions src/Environment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace GT\Config;

enum Environment:string {
case DEVELOPMENT = "development";
case STAGING = "staging";
case PRODUCTION = "production";
}
4 changes: 4 additions & 0 deletions src/EnvironmentConfigurationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace GT\Config;

class EnvironmentConfigurationException extends ConfigException {}
5 changes: 5 additions & 0 deletions src/IniParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ public function parse():Config {
INI_SCANNER_TYPED
);

if(isset($data["app"]["production"])
&& is_bool($data["app"]["production"])) {
$data["app"]["production"] = $data["app"]["production"] ? "1" : "0";
}

$configSectionList = [];
foreach($data as $sectionName => $sectionData) {
$configSectionList []= new ConfigSection(
Expand Down
Loading
Loading