SetupEnvCommand.php 2.6 KB

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