Skip to content

Instantly share code, notes, and snippets.

@hosni
Last active September 13, 2021 07:40
Show Gist options
  • Save hosni/6955e0ca686f59a3fde00638661f18cf to your computer and use it in GitHub Desktop.
Save hosni/6955e0ca686f59a3fde00638661f18cf to your computer and use it in GitHub Desktop.
key:generate command for lumen application
<?php
namespace App\Console\Commands;
use RuntimeException;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class KeyGenerateCommand extends Command
{
use ConfirmableTrait;
protected $signature = 'key:generate
{--show : Display the key instead of modifying files}
{--force : Force the operation to run when in production}';
protected $description = 'Set the application key';
public function handle(): void
{
$key = $this->generateRandomKey();
if ($this->option('show')) {
$this->line('<comment>' . $key . '</comment>');
return;
}
if (!$this->setKeyInEnvironmentFile($key)) {
return;
}
$this->laravel['config']['app.key'] = $key;
$this->info("Application key [$key] set successfully.");
}
protected function generateRandomKey(): string
{
return 'base64:' . base64_encode(random_bytes(
$this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
));
}
protected function setKeyInEnvironmentFile(string $key): bool
{
$currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');
if (strlen($currentKey) !== 0 && (!$this->confirmToProceed())) {
return false;
}
$this->writeNewEnvironmentFileWith($key);
return true;
}
protected function writeNewEnvironmentFileWith(string $key): void
{
$content = file_get_contents($this->laravel->basePath('.env'));
if ($content === false) {
throw new RuntimeException('can not read .env file');
}
file_put_contents($this->laravel->basePath('.env'), preg_replace(
$this->keyReplacementPattern(),
'APP_KEY=' . $key,
$content
));
}
protected function keyReplacementPattern(): string
{
$currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');
$escaped = preg_quote('=' . $currentKey, '/');
return "/^APP_KEY{$escaped}/m";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment