|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Frosh\Tools\Command; |
| 4 | + |
| 5 | +use Frosh\Tools\Components\Environment\EnvironmentManager; |
| 6 | +use Symfony\Component\Console\Command\Command; |
| 7 | +use Symfony\Component\Console\Input\InputArgument; |
| 8 | +use Symfony\Component\Console\Input\InputInterface; |
| 9 | +use Symfony\Component\Console\Input\InputOption; |
| 10 | +use Symfony\Component\Console\Output\OutputInterface; |
| 11 | + |
| 12 | +class EnvGetCommand extends Command |
| 13 | +{ |
| 14 | + public static $defaultName = 'frosh:env:get'; |
| 15 | + public static $defaultDescription = 'Get an environment variable'; |
| 16 | + private string $envPath; |
| 17 | + |
| 18 | + public function __construct(string $envPath) |
| 19 | + { |
| 20 | + parent::__construct(); |
| 21 | + $this->envPath = $envPath; |
| 22 | + } |
| 23 | + |
| 24 | + public function configure(): void |
| 25 | + { |
| 26 | + $this->addArgument('variable', InputArgument::OPTIONAL, 'Get specific environment variable'); |
| 27 | + $this->addOption('key-value', null, InputOption::VALUE_NONE, 'Get value as key value'); |
| 28 | + $this->addOption('json', null, InputOption::VALUE_NONE, 'Get value as json'); |
| 29 | + } |
| 30 | + |
| 31 | + public function execute(InputInterface $input, OutputInterface $output): int |
| 32 | + { |
| 33 | + if (!is_file($this->envPath)) { |
| 34 | + throw new \RuntimeException(\sprintf('Cannot use this command as env file is missing at %s', $this->envPath)); |
| 35 | + } |
| 36 | + |
| 37 | + $manager = new EnvironmentManager(); |
| 38 | + $file = $manager->read($this->envPath); |
| 39 | + $mode = $input->getOption('json') ? 'json' : ($input->getOption('key-value') ? 'kv' : ''); |
| 40 | + |
| 41 | + if ($input->getArgument('variable') === null) { |
| 42 | + if ($mode === 'json') { |
| 43 | + $output->writeln(json_encode($file->values(), JSON_PRETTY_PRINT)); |
| 44 | + } else if ($mode) { |
| 45 | + $output->writeln($file->__toString()); |
| 46 | + } |
| 47 | + |
| 48 | + return self::SUCCESS; |
| 49 | + } |
| 50 | + |
| 51 | + $var = $file->get($input->getArgument('variable')); |
| 52 | + |
| 53 | + if ($var === null) { |
| 54 | + throw new \RuntimeException(sprintf('Cannot find variable with name: %s', $input->getArgument('variable'))); |
| 55 | + } |
| 56 | + |
| 57 | + if ($mode === 'json') { |
| 58 | + $output->writeln(json_encode([$var->getKey() => $var->getValue()], JSON_PRETTY_PRINT)); |
| 59 | + } else if ($mode === 'kv') { |
| 60 | + $output->writeln($var->getLine()); |
| 61 | + } else { |
| 62 | + $output->writeln($var->getValue()); |
| 63 | + } |
| 64 | + |
| 65 | + return self::SUCCESS; |
| 66 | + } |
| 67 | +} |
0 commit comments