| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Console; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Jose\Component\Core\Util\Base64UrlSafe; |
| 9 | use Jose\Component\KeyManagement\JWKFactory; |
| 10 | use Symfony\Component\Console\Input\InputInterface; |
| 11 | use Symfony\Component\Console\Input\InputOption; |
| 12 | use function is_bool; |
| 13 | |
| 14 | abstract class GeneratorCommand extends ObjectOutputCommand |
| 15 | { |
| 16 | public function isEnabled(): bool |
| 17 | { |
| 18 | return class_exists(JWKFactory::class); |
| 19 | } |
| 20 | |
| 21 | protected function configure(): void |
| 22 | { |
| 23 | parent::configure(); |
| 24 | $this |
| 25 | ->addOption('use', 'u', InputOption::VALUE_OPTIONAL, 'Usage of the key. Must be either "sig" or "enc".') |
| 26 | ->addOption('alg', 'a', InputOption::VALUE_OPTIONAL, 'Algorithm for the key.') |
| 27 | ->addOption( |
| 28 | 'random_id', |
| 29 | null, |
| 30 | InputOption::VALUE_NONE, |
| 31 | 'If this option is set, a random key ID (kid) will be generated.' |
| 32 | ); |
| 33 | } |
| 34 | |
| 35 | protected function getOptions(InputInterface $input): array |
| 36 | { |
| 37 | $args = []; |
| 38 | $useRandomId = $input->getOption('random_id'); |
| 39 | if (! is_bool($useRandomId)) { |
| 40 | throw new InvalidArgumentException('Invalid value for option "random_id"'); |
| 41 | } |
| 42 | if ($useRandomId) { |
| 43 | $args['kid'] = $this->generateKeyID(); |
| 44 | } |
| 45 | foreach (['use', 'alg'] as $key) { |
| 46 | $value = $input->getOption($key); |
| 47 | if ($value !== null) { |
| 48 | $args[$key] = $value; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return $args; |
| 53 | } |
| 54 | |
| 55 | private function generateKeyID(): string |
| 56 | { |
| 57 | return Base64UrlSafe::encode(random_bytes(32)); |
| 58 | } |
| 59 | } |