SetupEnvCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. 'test6' => '.env.test6',
  32. 'test7' => '.env.test7',
  33. 'test8' => '.env.test8',
  34. 'test9' => '.env.test9',
  35. 'ci' => '.env.staging',
  36. ];
  37. private string $projectDir;
  38. #[Required]
  39. public function setProjectDir(string $projectDir): void
  40. {
  41. $this->projectDir = $projectDir;
  42. }
  43. /**
  44. * Configures the command.
  45. */
  46. protected function configure(): void
  47. {
  48. $this->addOption(
  49. 'host',
  50. null,
  51. InputOption::VALUE_REQUIRED,
  52. "Use this hostname instead of the current's host name."
  53. );
  54. }
  55. protected function execute(InputInterface $input, OutputInterface $output): int
  56. {
  57. if ($input->getOption('host')) {
  58. $hostname = $input->getOption('host');
  59. } elseif (getenv('HOST')) {
  60. $hostname = getenv('HOST');
  61. } else {
  62. $hostname = gethostname();
  63. }
  64. if (!array_key_exists($hostname, self::ENVIRONMENTS_FILES)) {
  65. throw new \RuntimeException('Critical : unknown environment ['.$hostname.']');
  66. }
  67. $envFile = Path::join($this->projectDir, 'env', self::ENVIRONMENTS_FILES[$hostname]);
  68. $symlinkLocation = Path::join($this->projectDir, '.env.local');
  69. if (file_exists($symlinkLocation)) {
  70. unlink($symlinkLocation);
  71. $output->writeln($symlinkLocation.' was deleted');
  72. }
  73. symlink($envFile, $symlinkLocation);
  74. $output->writeln('Symlink created : '.$symlinkLocation.' => '.$envFile);
  75. return Command::SUCCESS;
  76. }
  77. }