Skip to content

Commit

Permalink
✨ support for multi-environment setups
Browse files Browse the repository at this point in the history
⬆️ upgraded dependencies

Signed-off-by: Bruno Meilick <[email protected]>
  • Loading branch information
bnomei committed May 21, 2021
1 parent 56c0e37 commit ecc79e2
Show file tree
Hide file tree
Showing 81 changed files with 9,127 additions and 950 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
.idea
*.cache

/tests/.env
/tests/kirby
/tests/logs
/tests/site/accounts
Expand Down
89 changes: 26 additions & 63 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,94 +24,57 @@ This plugin is free but if you use it in a commercial project please consider to

## Setup

**.env file**
### .env file Examples
**/.env**
```
APP_MODE=production
APP_DEBUG=true
APP_DEBUG=false
ALGOLIA_APIKEY=12d7331a21d8a28b3069c49830f463e833e30f6d
KIRBY_API_USER=bnomei
KIRBY_API_PW=52d3a0edcc78be6c5645fdb7568f94d3d83d1c2a
```

**plugin helper methods**
```php
echo env('APP_MODE'); // production
// or
echo $page->getenv('ALGOLIA_APIKEY'); // 12d7331a21d8a28b3069c49830f463e833e30f6d
**/.env.staging**
```

**plain php**
```php
Bnomei\DotEnv::load();
echo getenv('APP_DEBUG'); // true
echo env('APP_DEBUG'); // true
APP_MODE=staging
APP_DEBUG=true
ALGOLIA_APIKEY=950306d052ec893b467f2ca088daf2964b9f9530
KIRBY_API_USER=notBnomei
KIRBY_API_PW=37e30ad867ff3a427317dcd1852abbd692b39ffc
```

### Using getenv() in the Kirby config file
## Usage everywhere but in Config files

**site/config/config.php (callbacks only)**
```php
<?php
return [
// ... other options
'bnomei.cloudconvert.apikey' => function() {
return getenv('CLOUDCONVERT_APIKEY');
},
'bnomei.instagram.token' => function() {
return getenv('INSTAGRAM_TOKEN');
},
'bnomei.thumbimageoptim.apikey' => function() {
return getenv('IMAGEOPTIM_APIKEY');
},
];
```
> ATTENTION: The PHP functions `getenv` or `putenv` are not supported by this plugin since v2. Do use super globals `$_ENV`, `$_SERVER` or the plugins helper `env()`.
**site/config/config.php (manual require class)**
**on server**
```php
<?php
// load dotenv plugins class
require_once __DIR__ . '/../plugins/kirby3-dotenv/classes/DotEnv.php';

return [
// ... other options
'bnomei.cloudconvert.apikey' =>
\Bnomei\DotEnv::getenv('CLOUDCONVERT_APIKEY'),
'bnomei.instagram.token' =>
\Bnomei\DotEnv::getenv('INSTAGRAM_TOKEN'),
'bnomei.thumbimageoptim.apikey' =>
\Bnomei\DotEnv::getenv('IMAGEOPTIM_APIKEY',
// provide options if defaults of plugin are not valid
[
'dir' => __DIR__ . '/../',
'file' => '.env.dev',
]
),
];
echo $_ENV['APP_MODE']; // production
echo env('APP_DEBUG'); // false
// or
echo $page->getenv('ALGOLIA_APIKEY'); // 12d7331a21d8a28b3069c49830f463e833e30f6d
```

#### No callback - no luck? 3 line are enough!
Unless you preload the `Bnomei\DotEnv` class using an `include_once` statement yourself the class will not be available in the kirby config files. But some options take a `callback` not just a `string` value. If your desired option does not then consider reporting a github issue at **their** repository. Adding a callback for an option is 3 lines of work.

**code/in/another/plugin.php**
**on staging server**
```php
public function thisIsWereAllConfigValuesAreLoaded()
{
$fancyOption = option('another.plugin.fancy');
// add these 3 lines
if (is_callable($fancyOptions)) {
$fancyOption = $fancyOption();
}
}
echo $_ENV['APP_MODE']; // staging
echo env('APP_DEBUG'); // true
// or
echo $page->getenv('ALGOLIA_APIKEY'); // 37e30ad867ff3a427317dcd1852abbd692b39ffc
```

## Usage in Config files

See [config examples](https://github.com/bnomei/kirby3-dotenv/tree/master/tests/site/config) on how to use this plugin in combination with kirbys config files. Since v2 this plugin support Kirbys [Multi-environment setup](https://getkirby.com/docs/guide/configuration#multi-environment-setup) used to merging multiple config files.

## Settings

| bnomei.dotenv. | Default | Description |
|---------------------------|----------------|---------------------------|
| dir | `callback` | returning `kirby()->roots()->index(). When installing Kirby 3 with Composer use a `function() { return realpath(kirby()->roots()->index() . '/../'); }` |
| filename | `.env` | |
| file | `.env` | |
| required | `[]` | You can define required variables in the Settings using an array. If any of these is missing a `RuntimeException` will be thrown. |
| setup | `callback` | perform additional tasks on raw dotenv class instance |

## Dependencies

Expand Down
58 changes: 32 additions & 26 deletions classes/DotEnv.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,43 +17,48 @@ final class DotEnv
*/
private $dotenv;

public function __construct(array $options = [], bool $fromConfig = true)
public function __construct(array $options = [], bool $useKirbyOptions = true)
{
$defaults = [
'dir' => $fromConfig ?
option('bnomei.dotenv.dir', kirby()->roots()->index()) :
'dir' => $useKirbyOptions ?
option('bnomei.dotenv.dir') :
realpath(__DIR__ . '/../../../../') // try plugin > site > index
,
'file' => $fromConfig ?
option('bnomei.dotenv.file', '.env') :
'file' => $useKirbyOptions ?
option('bnomei.dotenv.file') :
'.env'
,
'required' => $fromConfig ?
option('bnomei.dotenv.required', []) :
'required' => $useKirbyOptions ?
option('bnomei.dotenv.required') :
[]
,
'setup' => $useKirbyOptions ?
option('bnomei.dotenv.setup') :
function ($dotenv) {
return $dotenv;
},
];
$options = array_merge($defaults, $options);

foreach (['dir', 'file'] as $key) {
$value = A::get($options, $key);
if ($value && is_callable($value) && ! is_string($value)) {
$options[$key] = $value();
}
}

$this->dotenv = null;
$this->loadFromDir(A::get($options, 'dir'), A::get($options, 'file'));
$this->addRequired(A::get($options, 'required'));
$this->dotenv = A::get($options, 'setup')($this->dotenv);
}

private function loadFromDir($dir, $file = '.env'): bool
private function loadFromDir(string $dir, string $file): bool
{
if (! $dir) {
return false;
}
if (is_callable($dir)) {
$dir = $dir();
}
if (! $file) {
if (! $dir || ! $file) {
return false;
}
if (is_callable($file)) {
$file = $file();
}
$this->dotenv = new \Dotenv\Dotenv($dir, $file);
$this->dotenv = \Dotenv\Dotenv::createMutable($dir, $file);

try {
$this->dotenv->load();
Expand All @@ -78,17 +83,18 @@ public function addRequired(array $required = []): void
}

private static $singleton;
public static function load(array $options = [], bool $fromConfig = true): bool
public static function load(array $options = []): bool
{
if (! self::$singleton) {
self::$singleton = new self($options, $fromConfig);
}
// always load anew
self::$singleton = new self($options, count($options) === 0);
return self::$singleton->isLoaded();
}

public static function getenv(string $env, array $options = [])
public static function getenv(string $env)
{
self::load($options, count($options) === 0);
return getenv($env);
if (! self::$singleton) {
self::load();
}
return A::get($_ENV, $env, null);
}
}
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "bnomei/kirby3-dotenv",
"type": "kirby-plugin",
"version": "1.3.0",
"version": "2.0.0",
"description": "Kirby 3 Plugin for environment variables from .env",
"license": "MIT",
"authors": [
Expand All @@ -28,8 +28,8 @@
},
"require": {
"php": ">=7.3.0",
"vlucas/phpdotenv": "^2.6",
"getkirby/composer-installer": "^1.1"
"getkirby/composer-installer": "^1.1",
"vlucas/phpdotenv": "^5.3"
},
"scripts": {
"analyze": "phpstan analyse classes",
Expand Down
Loading

0 comments on commit ecc79e2

Please sign in to comment.