. */ namespace Sikofitt\GenerateMac\Command; use Sikofitt\GenerateMac\Mac; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\{ InvalidArgumentException, RuntimeException }; use Symfony\Component\Console\Input\{ InputInterface, InputOption }; use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class GenerateMacCommand extends Command { public function configure(): void { $this ->setName('generate-mac') ->addOption('count', 'c', InputOption::VALUE_REQUIRED, 'Generate {count} mac addresses.') ->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Output in this format instead of a string. [json,plain,string]') ->addOption('separator', 's', InputOption::VALUE_REQUIRED, 'The separator to use for mac addresses.') ; parent::configure(); } /** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * * @throws \Exception * @return int */ public function execute(InputInterface $input, OutputInterface $output): int { $count = (int)($input->getOption('count') ?? 1); if ($count <= 0) { throw new RuntimeException('$count should be a positive number greater than zero.'); } $separator = strtolower($input->getOption('separator') ?? 'colon'); if (!\in_array($separator, ['colon','none','dash'], true)) { throw new InvalidArgumentException('Separator must be one of "colon", "none", or "dash"'); } $outputFormat = strtolower($input->getOption('output') ?? 'string'); $io = new SymfonyStyle($input, $output); switch ($separator) { case 'colon': default: $separator = Mac::SEPARATOR_COLON; break; case 'none': $separator = Mac::SEPARATOR_NONE; break; case 'dash': $separator = Mac::SEPARATOR_DASH; break; } $mac = new Mac($separator); $macAddresses = $mac->getMacAddresses($count); switch ($outputFormat) { case 'string': default: $io->comment(sprintf('Generated %d mac addresses', $count)); $io->comment(implode(PHP_EOL, $macAddresses)); break; case 'json': $result = $count > 1 ? $macAddresses : [$macAddresses]; $io->writeln(\json_encode($result, JSON_PRETTY_PRINT)); break; case 'plain': $io->writeln($macAddresses, SymfonyStyle::OUTPUT_PLAIN | SymfonyStyle::VERBOSITY_NORMAL); break; } return 0; } }