Skip to content

[Dotenv] Reimplementing symfony/flex' dump-env as a Symfony command #42610

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

Merged
merged 2 commits into from
Sep 30, 2021
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
5 changes: 5 additions & 0 deletions src/Symfony/Component/Dotenv/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.4
---

* Add `dotenv:dump` command to compile the contents of the .env files into a PHP-optimized file called `.env.local.php`

5.1.0
-----

Expand Down
113 changes: 113 additions & 0 deletions src/Symfony/Component/Dotenv/Command/DotenvDumpCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Dotenv\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Symfony\Component\Dotenv\Dotenv;

/**
* A console command to compile .env files into a PHP-optimized file called .env.local.php.
*
* @internal
*/
#[Autoconfigure(bind: ['$dotenvPath' => '%kernel.project_dir%/.env', '$defaultEnv' => '%kernel.environment%'])]
final class DotenvDumpCommand extends Command
{
protected static $defaultName = 'dotenv:dump';
protected static $defaultDescription = 'Compiles .env files to .env.local.php';

private $dotenvPath;
private $defaultEnv;

public function __construct(string $dotenvPath, string $defaultEnv = null)
{
$this->dotenvPath = $dotenvPath;
$this->defaultEnv = $defaultEnv;

parent::__construct();
}

/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setDefinition([
new InputArgument('env', null === $this->defaultEnv ? InputArgument::REQUIRED : InputArgument::OPTIONAL, 'The application environment to dump .env files for - e.g. "prod".'),
])
->addOption('empty', null, InputOption::VALUE_NONE, 'Ignore the content of .env files')
->setHelp(<<<'EOT'
The <info>%command.name%</info> command compiles .env files into a PHP-optimized file called .env.local.php.

<info>%command.full_name%</info>
EOT
)
;
}

/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$env = $input->getArgument('env') ?? $this->defaultEnv;

if ($input->getOption('empty')) {
$vars = ['APP_ENV' => $env];
} else {
$vars = $this->loadEnv($env);
$env = $vars['APP_ENV'];
}

$vars = var_export($vars, true);
$vars = <<<EOF
<?php

// This file was generated by running "php bin/console dotenv:dump $env"

return $vars;

EOF;
file_put_contents($this->dotenvPath.'.local.php', $vars, \LOCK_EX);

$output->writeln(sprintf('Successfully dumped .env files in <info>.env.local.php</> for the <info>%s</> environment.', $env));

return 0;
}

private function loadEnv(string $env): array
{
$dotenv = new Dotenv();
$composerFile = \dirname($this->dotenvPath).'/composer.json';
$testEnvs = (is_file($composerFile) ? json_decode(file_get_contents($composerFile), true) : [])['extra']['runtime']['test_envs'] ?? ['test'];

$globalsBackup = [$_SERVER, $_ENV];
unset($_SERVER['APP_ENV']);
$_ENV = ['APP_ENV' => $env];
$_SERVER['SYMFONY_DOTENV_VARS'] = implode(',', array_keys($_SERVER));

try {
$dotenv->loadEnv($this->dotenvPath, null, 'dev', $testEnvs);
unset($_ENV['SYMFONY_DOTENV_VARS']);

return $_ENV;
} finally {
[$_SERVER, $_ENV] = $globalsBackup;
}
}
}
102 changes: 102 additions & 0 deletions src/Symfony/Component/Dotenv/Tests/Command/DotenvDumpCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Dotenv\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Dotenv\Command\DotenvDumpCommand;

class DotenvDumpCommandTest extends TestCase
{
protected function setUp(): void
{
file_put_contents(__DIR__.'/.env', <<<EOF
APP_ENV=dev
APP_SECRET=abc123
EOF
);

file_put_contents(__DIR__.'/.env.local', <<<EOF
APP_LOCAL=yes
EOF
);
}

protected function tearDown(): void
{
@unlink(__DIR__.'/.env');
@unlink(__DIR__.'/.env.local');
@unlink(__DIR__.'/.env.local.php');
@unlink(__DIR__.'/composer.json');
}

public function testExecute()
{
$command = $this->createCommand();
$command->execute([
'env' => 'test',
]);

$this->assertFileExists(__DIR__.'/.env.local.php');

$vars = require __DIR__.'/.env.local.php';
$this->assertSame([
'APP_ENV' => 'test',
'APP_SECRET' => 'abc123',
], $vars);
}

public function testExecuteEmpty()
{
$command = $this->createCommand();
$command->execute([
'env' => 'test',
'--empty' => true,
]);

$this->assertFileExists(__DIR__.'/.env.local.php');

$vars = require __DIR__.'/.env.local.php';
$this->assertSame(['APP_ENV' => 'test'], $vars);
}

public function testExecuteTestEnvs()
{
file_put_contents(__DIR__.'/composer.json', <<<EOF
{"extra":{"runtime":{"test_envs":[]}}}
EOF
);

$command = $this->createCommand();
$command->execute([
'env' => 'test',
]);

$this->assertFileExists(__DIR__.'/.env.local.php');

$vars = require __DIR__.'/.env.local.php';
$this->assertSame([
'APP_ENV' => 'test',
'APP_SECRET' => 'abc123',
'APP_LOCAL' => 'yes',
], $vars);
}

private function createCommand(): CommandTester
{
$application = new Application();
$application->add(new DotenvDumpCommand(__DIR__.'/.env'));

return new CommandTester($application->find('dotenv:dump'));
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Dotenv/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"symfony/deprecation-contracts": "^2.1"
},
"require-dev": {
"symfony/console": "^4.4|^5.0|^6.0",
"symfony/process": "^4.4|^5.0|^6.0"
},
"autoload": {
Expand Down