| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Console; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Jose\Component\KeyManagement\JWKFactory; |
| 9 | use Symfony\Component\Console\Attribute\AsCommand; |
| 10 | use Symfony\Component\Console\Input\InputArgument; |
| 11 | use Symfony\Component\Console\Input\InputInterface; |
| 12 | use Symfony\Component\Console\Input\InputOption; |
| 13 | use Symfony\Component\Console\Output\OutputInterface; |
| 14 | use function is_string; |
| 15 | |
| 16 | #[AsCommand(name: 'key:load:key', description: 'Loads a key from a key file (JWK format)',)] |
| 17 | final class KeyFileLoaderCommand extends GeneratorCommand |
| 18 | { |
| 19 | protected static $defaultName = 'key:load:key'; |
| 20 | |
| 21 | protected static $defaultDescription = 'Loads a key from a key file (JWK format)'; |
| 22 | |
| 23 | protected function configure(): void |
| 24 | { |
| 25 | parent::configure(); |
| 26 | $this->addArgument('file', InputArgument::REQUIRED, 'Filename of the key.') |
| 27 | ->addOption('secret', 's', InputOption::VALUE_OPTIONAL, 'Secret if the key is encrypted.', null); |
| 28 | } |
| 29 | |
| 30 | protected function execute(InputInterface $input, OutputInterface $output): int |
| 31 | { |
| 32 | $file = $input->getArgument('file'); |
| 33 | $password = $input->getOption('secret'); |
| 34 | if (! is_string($file)) { |
| 35 | throw new InvalidArgumentException('Invalid file'); |
| 36 | } |
| 37 | if ($password !== null && ! is_string($password)) { |
| 38 | throw new InvalidArgumentException('Invalid secret'); |
| 39 | } |
| 40 | $args = $this->getOptions($input); |
| 41 | |
| 42 | $jwk = JWKFactory::createFromKeyFile($file, $password, $args); |
| 43 | $this->prepareJsonOutput($input, $output, $jwk); |
| 44 | |
| 45 | return self::SUCCESS; |
| 46 | } |
| 47 | } |