SetupEnvCommand.php 2.5 KB

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