SetupEnvCommand.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Commands;
  3. use App\Service\Utils\Path;
  4. use Symfony\Component\Console\Attribute\AsCommand;
  5. use Symfony\Component\Console\Command\Command;
  6. use Symfony\Component\Console\Input\InputInterface;
  7. use Symfony\Component\Console\Input\InputOption;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use Symfony\Contracts\Service\Attribute\Required;
  10. /**
  11. * Post install script: create or replace the symlink .env.local pointing
  12. * to the .env file matching the current environment.
  13. *
  14. * @see doc/env.md
  15. */
  16. #[AsCommand(
  17. name: 'ot:setup:env',
  18. description: 'Setup the env file according to the current host'
  19. )]
  20. class SetupEnvCommand extends Command
  21. {
  22. public const ENVIRONMENTS_FILES = [
  23. 'ap2i' => '.env.docker',
  24. 'prod-v2' => '.env.prod',
  25. 'test-v2' => '.env.test',
  26. 'test1' => '.env.test1',
  27. 'test2' => '.env.test2',
  28. 'test3' => '.env.test3',
  29. 'test4' => '.env.test4',
  30. 'test5' => '.env.test5',
  31. 'ci' => '.env.staging',
  32. ];
  33. private string $projectDir;
  34. #[Required]
  35. public function setProjectDir(string $projectDir): void
  36. {
  37. $this->projectDir = $projectDir;
  38. }
  39. /**
  40. * Configures the command.
  41. */
  42. protected function configure(): void
  43. {
  44. $this->addOption(
  45. 'host',
  46. null,
  47. InputOption::VALUE_REQUIRED,
  48. "Use this hostname instead of the current's host name."
  49. );
  50. }
  51. protected function execute(InputInterface $input, OutputInterface $output): int
  52. {
  53. if ($input->getOption('host')) {
  54. $hostname = $input->getOption('host');
  55. } elseif (getenv('HOST')) {
  56. $hostname = getenv('HOST');
  57. } else {
  58. $hostname = gethostname();
  59. }
  60. if (!array_key_exists($hostname, self::ENVIRONMENTS_FILES)) {
  61. throw new \RuntimeException('Critical : unknown environment ['.$hostname.']');
  62. }
  63. $envFile = Path::join($this->projectDir, 'env', self::ENVIRONMENTS_FILES[$hostname]);
  64. $symlinkLocation = Path::join($this->projectDir, '.env.local');
  65. if (file_exists($symlinkLocation)) {
  66. unlink($symlinkLocation);
  67. $output->writeln($symlinkLocation.' was deleted');
  68. }
  69. symlink($envFile, $symlinkLocation);
  70. $output->writeln('Symlink created : '.$symlinkLocation.' => '.$envFile);
  71. return Command::SUCCESS;
  72. }
  73. }