|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illuminate\Foundation\Console; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | +use Illuminate\Encryption\Encrypter; |
| 7 | +use Illuminate\Filesystem\Filesystem; |
| 8 | +use Illuminate\Support\Str; |
| 9 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 10 | + |
| 11 | +#[AsCommand(name: 'env:encrypt')] |
| 12 | +class EnvironmentEncryptCommand extends Command |
| 13 | +{ |
| 14 | + /** |
| 15 | + * The name and signature of the console command. |
| 16 | + * |
| 17 | + * @var string |
| 18 | + */ |
| 19 | + protected $signature = 'env:encrypt |
| 20 | + {--key= : The encryption key} |
| 21 | + {--cipher= : The encryption cipher} |
| 22 | + {--file= : The environment file to be decrypted} |
| 23 | + {--force : Overwrite any existing files}'; |
| 24 | + |
| 25 | + /** |
| 26 | + * The name of the console command. |
| 27 | + * |
| 28 | + * This name is used to identify the command during lazy loading. |
| 29 | + * |
| 30 | + * @var string|null |
| 31 | + * |
| 32 | + * @deprecated |
| 33 | + */ |
| 34 | + protected static $defaultName = 'env:encrypt'; |
| 35 | + |
| 36 | + /** |
| 37 | + * The console command description. |
| 38 | + * |
| 39 | + * @var string |
| 40 | + */ |
| 41 | + protected $description = 'Encrypt the given environment file'; |
| 42 | + |
| 43 | + /** |
| 44 | + * The filesystem instance. |
| 45 | + * |
| 46 | + * @var \Illuminate\Filesystem\Filesystem |
| 47 | + */ |
| 48 | + protected $files; |
| 49 | + |
| 50 | + public function __construct(Filesystem $files) |
| 51 | + { |
| 52 | + parent::__construct(); |
| 53 | + |
| 54 | + $this->files = $files; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Execute the console command. |
| 59 | + * |
| 60 | + * @return void |
| 61 | + */ |
| 62 | + public function handle() |
| 63 | + { |
| 64 | + $key = $this->option('key') ?: Str::random(16); |
| 65 | + $cipher = $this->option('cipher') ?: 'aes-128-cbc'; |
| 66 | + $environment = $this->option('file') ?: $this->laravel->environmentFilePath(); |
| 67 | + $encrypted = $environment.'.encrypted'; |
| 68 | + |
| 69 | + if (! $this->files->exists($environment)) { |
| 70 | + return $this->components->error("The environment file {$environment} does not exist."); |
| 71 | + } |
| 72 | + |
| 73 | + if ($this->files->exists($encrypted) && ! $this->option('force')) { |
| 74 | + return $this->components->error("The encrypted environment file {$encrypted} already exists."); |
| 75 | + } |
| 76 | + |
| 77 | + $encrypter = new Encrypter($key, $cipher); |
| 78 | + |
| 79 | + $this->files->put($encrypted, $encrypter->encrypt($this->files->get($environment))); |
| 80 | + |
| 81 | + $this->components->info("The environment file {$environment} has been encrypted using they key {$key}."); |
| 82 | + } |
| 83 | +} |
0 commit comments