Просмотр файла app/Commands/KeyGenerate.php

Размер файла: 1.67Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Commands;
  6.  
  7. use Illuminate\Support\Str;
  8. use Phinx\Console\Command\AbstractCommand;
  9. use Symfony\Component\Console\Input\InputInterface;
  10. use Symfony\Component\Console\Output\OutputInterface;
  11.  
  12. class KeyGenerate extends AbstractCommand
  13. {
  14. /**
  15. * {@inheritdoc}
  16. */
  17. protected function configure(): void
  18. {
  19. parent::configure();
  20.  
  21. $this->setName('key:generate')
  22. ->setDescription('Set the application key');
  23. }
  24.  
  25. /**
  26. * Setting application key
  27. *
  28. * @param InputInterface $input
  29. * @param OutputInterface $output
  30. *
  31. * @return int
  32. */
  33. protected function execute(InputInterface $input, OutputInterface $output): int
  34. {
  35. $key = Str::random(32);
  36. $this->writeNewEnvironmentFileWith($key);
  37.  
  38. $output->writeln('<info>Application key ['.$key.'] set successfully.</info>');
  39.  
  40. return 0;
  41. }
  42.  
  43. /**
  44. * Write a new environment file with the given key.
  45. *
  46. * @param string $key
  47. *
  48. * @return void
  49. */
  50. protected function writeNewEnvironmentFileWith($key): void
  51. {
  52. if (is_writable(BASEDIR . '/.env')) {
  53. file_put_contents(BASEDIR . '/.env', preg_replace(
  54. $this->keyReplacementPattern(),
  55. 'APP_KEY=' . $key,
  56. file_get_contents(BASEDIR . '/.env')
  57. ));
  58. }
  59. }
  60.  
  61. /**
  62. * Get a regex pattern that will match env APP_KEY with any random key.
  63. *
  64. * @return string
  65. */
  66. protected function keyReplacementPattern(): string
  67. {
  68. $escaped = preg_quote('=' . config('app.key'), '/');
  69. return "/^APP_KEY{$escaped}/m";
  70. }
  71. }