Skip to content

Commit

Permalink
✨ can be used in config without callback after loading class
Browse files Browse the repository at this point in the history
Signed-off-by: Bruno Meilick <[email protected]>
  • Loading branch information
bnomei committed May 20, 2021
1 parent 3a1c02b commit 56c0e37
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 48 deletions.
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,46 @@ echo env('APP_DEBUG'); // true

### Using getenv() in the Kirby config file

**site/config/config.php**
**site/config/config.php (callbacks only)**
```php
<?php
return [
// ... other options
'bnomei.cloudconvert.apikey' => function() {
return env('CLOUDCONVERT_APIKEY');
return getenv('CLOUDCONVERT_APIKEY');
},
'bnomei.instagram.token' => function() {
return env('INSTAGRAM_TOKEN');
return getenv('INSTAGRAM_TOKEN');
},
'bnomei.thumbimageoptim.apikey' => function() {
return env('IMAGEOPTIM_APIKEY');
return getenv('IMAGEOPTIM_APIKEY');
},
];
```

**site/config/config.php (manual require class)**
```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',
]
),
];
```

#### 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.

Expand Down
37 changes: 27 additions & 10 deletions classes/DotEnv.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Dotenv\Exception\InvalidPathException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\F;
use function getenv;
use function option;

Expand All @@ -16,27 +17,43 @@ final class DotEnv
*/
private $dotenv;

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

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

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

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

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

public static function getenv(string $env)
public static function getenv(string $env, array $options = [])
{
self::load();
self::load($options, count($options) === 0);
return getenv($env);
}
}
8 changes: 7 additions & 1 deletion 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.2.3",
"version": "1.3.0",
"description": "Kirby 3 Plugin for environment variables from .env",
"license": "MIT",
"authors": [
Expand Down Expand Up @@ -42,6 +42,12 @@
"dist": [
"composer install --no-dev --optimize-autoloader",
"git rm -rf --cached .; git add .;"
],
"kirby": [
"composer install",
"composer update",
"composer install --working-dir=tests/kirby --no-dev --optimize-autoloader",
"composer update --working-dir=tests/kirby"
]
},
"require-dev": {
Expand Down
14 changes: 7 additions & 7 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
stopOnFailure="false">
<testsuites>
<testsuite name="PLUGIN">
<directory suffix="Test.php">./tests</directory>
<file>./tests/DotEnvTest.php</file>
</testsuite>
</testsuites>
<php>
Expand Down
51 changes: 34 additions & 17 deletions tests/DotEnvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ class DotEnvTest extends TestCase
{
public function setUp(): void
{
copy(
__DIR__ . '/.env.example',
__DIR__ . '/.env'
);
if (!file_exists(__DIR__ . '/.env')) {
copy(
__DIR__ . '/.env.example',
__DIR__ . '/.env'
);
}
}

public function tearDown(): void
public function removeDotEnvFile(): void
{
$dotenv = __DIR__ . '/.env';
if (file_exists($dotenv)) {
Expand All @@ -35,18 +37,6 @@ public function testLoad()
$this->assertTrue($dotenv->isLoaded());
}

public function testLoadFailsIfMissingFile()
{
self::tearDown(); // early
$dotenv = new Bnomei\DotEnv();
$this->assertFalse($dotenv->isLoaded());

$dotenv = new Bnomei\DotEnv([
'dir' => null
]);
$this->assertFalse($dotenv->isLoaded());
}

public function testRequired()
{
$dotenv = new Bnomei\DotEnv([
Expand All @@ -70,4 +60,31 @@ public function testStaticLoad()
{
$this->assertTrue(Bnomei\DotEnv::load());
}

public function testLoadedToPage()
{
$response = kirby()->render("/");
$this->assertTrue($response->code() === 200);
$this->assertMatchesRegularExpression('/(production)/', $response->body());
}

public function testLoadedFromConfig()
{
$this->assertEquals('bnomei', kirby()->option('no_callback'));
}

public function testLoadFailsIfMissingFile()
{
$this->removeDotEnvFile();

$dotenv = new Bnomei\DotEnv();
$this->assertFalse($dotenv->isLoaded());

$dotenv = new Bnomei\DotEnv([
'dir' => null,
]);
$this->assertFalse($dotenv->isLoaded());

$this->setUp();
}
}
14 changes: 14 additions & 0 deletions tests/site/config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

// load dotenv plugins class
require_once __DIR__ . '/../../../classes/DotEnv.php';

return [
'no_callback' => \Bnomei\DotEnv::getenv(
'KIRBY_API_USER',
[
'dir' => realpath(__DIR__ . '/../../'),
'file' => '.env',
],
),
];
2 changes: 2 additions & 0 deletions tests/site/templates/default.php
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
<?php

echo $page->getenv('APP_MODE');
8 changes: 4 additions & 4 deletions vendor/composer/InstalledVersions.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ class InstalledVersions
private static $installed = array (
'root' =>
array (
'pretty_version' => '1.2.3',
'version' => '1.2.3.0',
'pretty_version' => '1.3.0',
'version' => '1.3.0.0',
'aliases' =>
array (
),
Expand All @@ -39,8 +39,8 @@ class InstalledVersions
array (
'bnomei/kirby3-dotenv' =>
array (
'pretty_version' => '1.2.3',
'version' => '1.2.3.0',
'pretty_version' => '1.3.0',
'version' => '1.3.0.0',
'aliases' =>
array (
),
Expand Down
8 changes: 4 additions & 4 deletions vendor/composer/installed.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php return array (
'root' =>
array (
'pretty_version' => '1.2.3',
'version' => '1.2.3.0',
'pretty_version' => '1.3.0',
'version' => '1.3.0.0',
'aliases' =>
array (
),
Expand All @@ -13,8 +13,8 @@
array (
'bnomei/kirby3-dotenv' =>
array (
'pretty_version' => '1.2.3',
'version' => '1.2.3.0',
'pretty_version' => '1.3.0',
'version' => '1.3.0.0',
'aliases' =>
array (
),
Expand Down

0 comments on commit 56c0e37

Please sign in to comment.