Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Environments #445

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
15 changes: 3 additions & 12 deletions autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,10 @@

declare(strict_types=1);

use Dotenv\Dotenv;
use App\Env;

require_once __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$_SERVER['YII_ENV'] = $_ENV['YII_ENV'] = Env::get('YII_ENV');

$_ENV['YII_ENV'] = empty($_ENV['YII_ENV']) ? null : (string)$_ENV['YII_ENV'];
$_SERVER['YII_ENV'] = $_ENV['YII_ENV'];

$_ENV['YII_DEBUG'] = filter_var(
!empty($_ENV['YII_DEBUG']) ? $_ENV['YII_DEBUG'] : true,
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
) ?? true;
$_SERVER['YII_DEBUG'] = $_ENV['YII_DEBUG'];
$_SERVER['YII_DEBUG'] = $_ENV['YII_DEBUG'] = Env::getBoolean('YII_DEBUG');
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@
"post-create-project-cmd": [
"App\\Installer::copyEnvFile"
],
"post-autoload-dump": [
"App\\Env::load"
],
"test": "phpunit --testdox --no-interaction",
"test-watch": "phpunit-watcher watch"
},
Expand Down
3 changes: 2 additions & 1 deletion config/common/router.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use App\Env;
use Yiisoft\Config\Config;
use Yiisoft\DataResponse\Middleware\FormatDataResponse;
use Yiisoft\Csrf\CsrfMiddleware;
Expand All @@ -23,7 +24,7 @@
->routes(...$config->get('routes'))
);

if (!str_starts_with(getenv('YII_ENV') ?: '', 'prod')) {
if (!str_starts_with(Env::get('YII_ENV', ''), 'prod')) {
$collector->middleware(ToolbarMiddleware::class);
}

Expand Down
10 changes: 5 additions & 5 deletions config/params.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use App\Env;
use App\Middleware\LocaleMiddleware;
use App\ViewInjection\CommonViewInjection;
use App\ViewInjection\LayoutViewInjection;
Expand Down Expand Up @@ -87,7 +88,7 @@
],

'yiisoft/router-fastroute' => [
'enableCache' => false,
'enableCache' => !Env::getBoolean('YII_DEBUG'),
],

'yiisoft/translator' => [
Expand Down Expand Up @@ -188,10 +189,9 @@
* ],
* ]
*/
'schema-providers' => [
// Uncomment next line to enable a Schema caching in the common cache
// \Yiisoft\Yii\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class => ['key' => 'cycle-orm-cache-key'],

'schema-providers' => (Env::getBoolean('YII_DEBUG') ? [] : [
\Yiisoft\Yii\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class => ['key' => 'cycle-orm-cache-key'],
]) + [
// Store generated Schema in the file
\Yiisoft\Yii\Cycle\Schema\Provider\PhpFileSchemaProvider::class => [
'mode' => \Yiisoft\Yii\Cycle\Schema\Provider\PhpFileSchemaProvider::MODE_WRITE_ONLY,
Expand Down
2 changes: 1 addition & 1 deletion config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
fn (HttpCache $httpCache, PostRepository $postRepository, CurrentRoute $currentRoute) =>
$httpCache->withEtagSeed(function (ServerRequestInterface $request, $params) use ($postRepository, $currentRoute) {
$post = $postRepository->findBySlug($currentRoute->getArgument('slug'));
return $post->getSlug() . '-' . $post->getUpdatedAt()->getTimestamp();
return $post?->getSlug() . '-' . $post?->getUpdatedAt()->getTimestamp();
})
)
->action([PostController::class, 'index'])
Expand Down
61 changes: 61 additions & 0 deletions src/Env.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace App;

use Dotenv\Dotenv;
use Yiisoft\VarDumper\VarDumper;

final class Env
{
private static ?array $values = null;

private const FILE_NAME = '.env.php';

public static function get(string $name, string $default = null): ?string
{
self::ensureValuesLoaded();

return isset(self::$values[$name]) ? (string)self::$values[$name] : getenv($default) ?? $default;
}

public static function getBoolean(string $name, bool $default = false): bool
{
self::ensureValuesLoaded();

return \filter_var(self::$values[$name] ?? null, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $default;
}

public static function getInteger(string $name, int $default = 0): int
{
self::ensureValuesLoaded();

return \filter_var(self::$values[$name] ?? null, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? $default;
}

public static function load(): void
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe move this method to separate class? In most cases this method will be unnecessary in IDE autocompletion on Env::.

{
$dotenv = Dotenv::createArrayBacked(dirname(__DIR__));
$values = $dotenv->load();
$values = VarDumper::create($values)->export();
$content = <<<PHP
<?php

declare(strict_types=1);

return $values;

PHP;

file_put_contents(dirname(__DIR__) . '/runtime/' . self::FILE_NAME, $content, LOCK_EX);
}

private static function ensureValuesLoaded(): void
{
if (self::$values === null) {
$values = require dirname(__DIR__) . '/runtime/' . self::FILE_NAME;
self::$values = $values + $_ENV + $_SERVER;
}
}
}