|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Syntatis\Version\CLI\Commands; |
| 6 | + |
| 7 | +use Symfony\Component\Console\Command\Command; |
| 8 | +use Symfony\Component\Console\Input\InputArgument; |
| 9 | +use Symfony\Component\Console\Input\InputInterface; |
| 10 | +use Symfony\Component\Console\Output\OutputInterface; |
| 11 | +use Symfony\Component\Console\Style\SymfonyStyle; |
| 12 | +use Throwable; |
| 13 | +use TypeError; |
| 14 | +use Version\Version; |
| 15 | + |
| 16 | +use function gettype; |
| 17 | +use function is_string; |
| 18 | +use function sprintf; |
| 19 | + |
| 20 | +final class ValidateCommand extends Command |
| 21 | +{ |
| 22 | + /** |
| 23 | + * Configure the command options and arguments. |
| 24 | + */ |
| 25 | + protected function configure(): void |
| 26 | + { |
| 27 | + $this->setName('validate'); |
| 28 | + $this->setDescription('Validate a version.'); |
| 29 | + $this->setHelp('This command checks if the provided value is a valid Semantic Version (SemVer) version format.'); |
| 30 | + $this->setAliases(['val']); |
| 31 | + $this->addArgument('version', InputArgument::REQUIRED, 'Version to validate'); |
| 32 | + } |
| 33 | + |
| 34 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 35 | + { |
| 36 | + $style = new SymfonyStyle($input, $output); |
| 37 | + $version = $input->getArgument('version'); |
| 38 | + |
| 39 | + try { |
| 40 | + if (is_string($version)) { |
| 41 | + Version::fromString($version); |
| 42 | + $style->success(sprintf("Version string '%s' is valid and can be parsed", $version)); |
| 43 | + |
| 44 | + return Command::SUCCESS; |
| 45 | + } |
| 46 | + |
| 47 | + throw new TypeError(sprintf("Invalid type of value to validate. Expected string, '%s' given", gettype($version))); |
| 48 | + } catch (Throwable $th) { |
| 49 | + $style->error($th->getMessage()); |
| 50 | + |
| 51 | + return Command::FAILURE; |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments