Skip to content

Add "dump-env" command to compile .env files to .env.local.php #449

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
Jan 21, 2019
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
},
"require-dev": {
"composer/composer": "^1.0.2",
"symfony/dotenv": "^3.4|^4.0",
"symfony/phpunit-bridge": "^3.4.19|^4.1.8",
"symfony/process": "^2.7|^3.0|^4.0"
},
Expand Down
2 changes: 1 addition & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
<phpunit backupGlobals="true"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
Expand Down
102 changes: 102 additions & 0 deletions src/Command/DumpEnvCommand.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 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Flex\Command;

use Composer\Command\BaseCommand;
use Composer\Config;
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\Dotenv\Dotenv;
use Symfony\Flex\Options;

class DumpEnvCommand extends BaseCommand
{
private $config;
private $options;

public function __construct(Config $config, Options $options)
{
$this->config = $config;
$this->options = $options;

parent::__construct();
}

protected function configure()
{
$this->setName('symfony:dump-env')
->setAliases(['dump-env'])
->setDescription('Compiles .env files to .env.local.php.')
->setDefinition([
new InputArgument('env', InputArgument::REQUIRED, 'The application environment to dump .env files for - e.g. "prod".'),
])
->addOption('empty', null, InputOption::VALUE_NONE, 'Ignore the content of .env files')
;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
$_SERVER['APP_ENV'] = $env = $input->getArgument('env');
$path = $this->options->get('root-dir').'/.env';

if (!$input->getOption('empty')) {
$this->loadEnv($path, $env);
}

$vars = array_flip(explode(',', ($_SERVER['SYMFONY_DOTENV_VARS'] ?? '').',APP_ENV'));
$vars = array_intersect_key($_SERVER, $vars);
$vars = var_export($vars, true);
$vars = <<<EOF
<?php

// This file was generated by running "composer dump-env $env"

return $vars;

EOF;
file_put_contents($path.'.local.php', $vars, LOCK_EX);

$this->getIO()->writeError('Successfully dumped .env files in <info>.env.local.php</>');
}

private function loadEnv(string $path, string $env)
{
require $this->config->get('vendor-dir').'/autoload.php';

if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}

$dotenv = new Dotenv();

if (method_exists($dotenv, 'loadEnv')) {
$dotenv->loadEnv($path);
} else {
// fallback code in case your Dotenv component is not 4.2 or higher (when loadEnv() was added)
$dotenv->load(file_exists($path) || !file_exists($p = "$path.dist") ? $path : $p);

if ('test' !== $env && file_exists($p = "$path.local")) {
$dotenv->load($p);
}

if (file_exists($p = "$path.$env")) {
$dotenv->load($p);
}

if (file_exists($p = "$path.$env.local")) {
$dotenv->load($p);
}
}
}
}
1 change: 1 addition & 0 deletions src/Flex.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ public function activate(Composer $composer, IOInterface $io)
$app->add(new Command\UnpackCommand($resolver));
$app->add(new Command\SyncRecipesCommand($this));
$app->add(new Command\GenerateIdCommand($this));
$app->add(new Command\DumpEnvCommand($this->config, $this->options));

break;
}
Expand Down
98 changes: 98 additions & 0 deletions tests/Command/DumpEnvCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

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

namespace Symfony\Flex\Tests\Command;

use Composer\Config;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Flex\Command\DumpEnvCommand;
use Symfony\Flex\Options;

class DumpEnvCommandTest extends TestCase
{
public function testFileIsCreated()
{
@mkdir(FLEX_TEST_DIR);
$env = FLEX_TEST_DIR.'/.env';
$envLocal = FLEX_TEST_DIR.'/.env.local.php';
@unlink($env);
@unlink($envLocal);

$envContent = <<<EOF
APP_ENV=dev
APP_SECRET=abcdefgh123456789
EOF;
file_put_contents($env, $envContent);

$command = $this->createCommandDumpEnv();
$command->execute([
'env' => 'prod',
]);

$this->assertFileExists($envLocal);

$vars = require $envLocal;
$this->assertSame([
'APP_ENV' => 'prod',
'APP_SECRET' => 'abcdefgh123456789',
], $vars);

unlink($env);
unlink($envLocal);
}

public function testEmptyOptionMustIgnoreContent()
{
@mkdir(FLEX_TEST_DIR);
$env = FLEX_TEST_DIR.'/.env';
$envLocal = FLEX_TEST_DIR.'/.env.local.php';
@unlink($env);
@unlink($envLocal);

$envContent = <<<EOF
APP_ENV=dev
APP_SECRET=abcdefgh123456789
EOF;
file_put_contents($env, $envContent);

$command = $this->createCommandDumpEnv();
$command->execute([
'env' => 'prod',
'--empty' => true,
]);

$this->assertFileExists($envLocal);

$vars = require $envLocal;
$this->assertSame([
'APP_ENV' => 'prod',
], $vars);

unlink($env);
unlink($envLocal);
}

private function createCommandDumpEnv()
{
$command = new DumpEnvCommand(
new Config(false, __DIR__.'/../..'),
new Options(['root-dir' => FLEX_TEST_DIR])
);

$application = new Application();
$application->add($command);
$command = $application->find('dump-env');

return new CommandTester($command);
}
}