Created
March 8, 2020 12:23
-
-
Save daalvand/686fff00f33ff59ad50e162abd659b6c to your computer and use it in GitHub Desktop.
lumen Key Generate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Console\Commands; | |
| use Illuminate\Console\Command; | |
| use Illuminate\Encryption\Encrypter; | |
| class KeyGenerateCommand extends Command | |
| { | |
| /** | |
| * The console command name. | |
| * | |
| * @var string | |
| */ | |
| protected $name = 'key:generate'; | |
| 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 handle() { | |
| $key = $this->generateRandomKey(); | |
| if ($this->option('show')) { | |
| $this->comment($key); | |
| exit(); | |
| } | |
| // 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->writeNewEnvironmentFileWith($key); | |
| $this->laravel['config']['app.key'] = $key; | |
| $this->info("Application key [$key] set successfully."); | |
| exit(); | |
| } | |
| /** | |
| * Generate a random key for the application. | |
| * | |
| * @return string | |
| */ | |
| protected function generateRandomKey() { | |
| return 'base64:' . base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher'])); | |
| } | |
| /** | |
| * Write a new environment file with the given key. | |
| * | |
| * @param string $key | |
| * | |
| * @return void | |
| */ | |
| protected function writeNewEnvironmentFileWith($key) { | |
| $envPath = base_path('.env'); | |
| if(!file_exists($envPath)){ | |
| exec("cp $envPath.example $envPath"); | |
| } | |
| file_put_contents($envPath, preg_replace($this->keyReplacementPattern(),'APP_KEY=' . $key,file_get_contents($envPath))); | |
| } | |
| /** | |
| * Get a regex pattern that will match env APP_KEY with any random key. | |
| * | |
| * @return string | |
| */ | |
| protected function keyReplacementPattern() { | |
| $escaped = preg_quote('=' . getenv('APP_KEY'), '/'); | |
| return "/^APP_KEY{$escaped}/m"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment