Skip to content

Instantly share code, notes, and snippets.

@f3ath
Created December 4, 2016 21:31
Show Gist options
  • Save f3ath/e516fe879a76c644d347be5847e27356 to your computer and use it in GitHub Desktop.
Save f3ath/e516fe879a76c644d347be5847e27356 to your computer and use it in GitHub Desktop.
<?php
class Config
{
/**
* @var string
*/
private $root;
public function __construct(string $root)
{
$this->root = $root;
}
public function configure(\ArrayAccess $app, string $env = null)
{
if (empty($env)) {
$env = getenv('APP_ENV') ?: 'prod';
}
$config = array_merge(
$this->getDefaultConfig(),
$this->getConfig($env)
);
$secure_json = $config['secure_json'];
if ($secure_json && file_exists($secure_json)) {
$config = array_replace_recursive(
$config,
json_decode(file_get_contents($secure_json), true)
);
}
$app['config'] = $config;
$app['env'] = $env;
foreach ($config['application'] as $key => $val) {
$app[$key] = $val;
}
array_map(
function (string $service) use ($app) {
include $service;
},
$config['services']
);
}
protected function getConfig(string $env): array
{
$path = "{$this->root}/{$env}.php";
if (file_exists($path)) {
return include $path;
}
throw new \InvalidArgumentException("Nonexistent environment: $env");
}
protected function getDefaultConfig(): array
{
return [
'secure_json' => false,
'services' => [],
'application' => [],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment