Skip to content

Instantly share code, notes, and snippets.

@milanarandjelovic
Last active May 29, 2017 18:14
Show Gist options
  • Save milanarandjelovic/399b18bb3f8e652aadbb21b407936d2b to your computer and use it in GitHub Desktop.
Save milanarandjelovic/399b18bb3f8e652aadbb21b407936d2b to your computer and use it in GitHub Desktop.
Laravel\Lumen Key Generator Commands
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class KeyGenerateCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'key:generate {--show : Display the key instead of modifying files}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the application key';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->generateRandomKey();
if ($this->option('show')) {
return $this->line('<comment>' . $key . '</comment>');
}
// Next, we will replace the application key in the environment file so it is
// automatically setup for this developer. This key gets generated using a
// secure random byte generator and is later base64 encoded for storage.
$this->setKeyInEnvironmentFile($key);
$this->laravel['config']['app.key'] = $key;
$this->info("Application key [$key] set successfully.");
}
/**
* Set the environment key in the environment file.
*
* @param string $key
* @return void
*/
protected function setKeyInEnvironmentFile($key)
{
file_put_contents($this->laravel->basePath('.env'), str_replace(
'APP_KEY=' . $this->laravel['config']['app.key'],
'APP_KEY=' . $key,
file_get_contents($this->laravel->basePath('.env'))
));
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function generateRandomKey()
{
return 'base64:' . base64_encode(random_bytes(
$this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment