| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Console; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Jose\Component\Core\JWK; |
| 9 | use Jose\Component\Core\JWKSet; |
| 10 | use Jose\Component\Core\Util\JsonConverter; |
| 11 | use Symfony\Component\Console\Attribute\AsCommand; |
| 12 | use Symfony\Component\Console\Input\InputArgument; |
| 13 | use Symfony\Component\Console\Input\InputInterface; |
| 14 | use Symfony\Component\Console\Output\OutputInterface; |
| 15 | use function count; |
| 16 | use function is_array; |
| 17 | use function is_string; |
| 18 | |
| 19 | #[AsCommand(name: 'keyset:rotate', description: 'Rotate a key set.',)] |
| 20 | final class RotateKeysetCommand extends ObjectOutputCommand |
| 21 | { |
| 22 | protected static $defaultName = 'keyset:rotate'; |
| 23 | |
| 24 | protected static $defaultDescription = 'Rotate a key set.'; |
| 25 | |
| 26 | protected function configure(): void |
| 27 | { |
| 28 | parent::configure(); |
| 29 | $this->setHelp('This command removes the last key in a key set a place a new one at the beginning.') |
| 30 | ->addArgument('jwkset', InputArgument::REQUIRED, 'The JWKSet object') |
| 31 | ->addArgument('jwk', InputArgument::REQUIRED, 'The new JWK object'); |
| 32 | } |
| 33 | |
| 34 | protected function execute(InputInterface $input, OutputInterface $output): int |
| 35 | { |
| 36 | $jwkset = $this->getKeyset($input) |
| 37 | ->all(); |
| 38 | $jwk = $this->getKey($input); |
| 39 | |
| 40 | if (count($jwkset) !== 0) { |
| 41 | array_pop($jwkset); |
| 42 | } |
| 43 | array_unshift($jwkset, $jwk); |
| 44 | |
| 45 | $this->prepareJsonOutput($input, $output, new JWKSet($jwkset)); |
| 46 | |
| 47 | return self::SUCCESS; |
| 48 | } |
| 49 | |
| 50 | private function getKeyset(InputInterface $input): JWKSet |
| 51 | { |
| 52 | $jwkset = $input->getArgument('jwkset'); |
| 53 | if (! is_string($jwkset)) { |
| 54 | throw new InvalidArgumentException('Invalid JWKSet'); |
| 55 | } |
| 56 | $json = JsonConverter::decode($jwkset); |
| 57 | if (! is_array($json)) { |
| 58 | throw new InvalidArgumentException('Invalid JWKSet'); |
| 59 | } |
| 60 | |
| 61 | return JWKSet::createFromKeyData($json); |
| 62 | } |
| 63 | |
| 64 | private function getKey(InputInterface $input): JWK |
| 65 | { |
| 66 | $jwk = $input->getArgument('jwk'); |
| 67 | if (! is_string($jwk)) { |
| 68 | throw new InvalidArgumentException('Invalid JWK'); |
| 69 | } |
| 70 | $json = JsonConverter::decode($jwk); |
| 71 | if (! is_array($json)) { |
| 72 | throw new InvalidArgumentException('Invalid JWK'); |
| 73 | } |
| 74 | |
| 75 | return new JWK($json); |
| 76 | } |
| 77 | } |