|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TypistTech\PhpMatrix\Console; |
| 6 | + |
| 7 | +use RuntimeException; |
| 8 | +use Symfony\Component\Console\Attribute\Argument; |
| 9 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 10 | +use Symfony\Component\Console\Command\Command; |
| 11 | +use Symfony\Component\Console\Style\SymfonyStyle; |
| 12 | +use TypistTech\PhpMatrix\Versions; |
| 13 | +use UnexpectedValueException; |
| 14 | + |
| 15 | +#[AsCommand( |
| 16 | + name: 'constraint', |
| 17 | + description: 'List PHP versions that satisfy the given constraint', |
| 18 | +)] |
| 19 | +class ConstraintCommand extends Command |
| 20 | +{ |
| 21 | + use PrintErrorTrait; |
| 22 | + |
| 23 | + public function __construct( |
| 24 | + private readonly MatrixFactory $matrixFactory = new MatrixFactory, |
| 25 | + ) { |
| 26 | + parent::__construct(); |
| 27 | + } |
| 28 | + |
| 29 | + public function __invoke( |
| 30 | + SymfonyStyle $io, |
| 31 | + #[Argument(description: 'The version constraint.')] |
| 32 | + string $constraint, |
| 33 | + #[SourceOption] |
| 34 | + string $source = Source::Auto->value, |
| 35 | + #[ModeOption] |
| 36 | + string $mode = Mode::MinorOnly->value, |
| 37 | + ): int { |
| 38 | + $matrix = $this->matrixFactory->make( |
| 39 | + Source::fromValue($source), |
| 40 | + Mode::fromValue($mode), |
| 41 | + ); |
| 42 | + |
| 43 | + try { |
| 44 | + $versions = $matrix->satisfiedBy($constraint); |
| 45 | + } catch (UnexpectedValueException $e) { |
| 46 | + $this->printError( |
| 47 | + $io, |
| 48 | + $e->getMessage() |
| 49 | + ); |
| 50 | + |
| 51 | + return Command::FAILURE; |
| 52 | + } |
| 53 | + |
| 54 | + if (empty($versions)) { |
| 55 | + $this->printError( |
| 56 | + $io, |
| 57 | + sprintf('No PHP versions could satisfy the constraint "%s".', $constraint) |
| 58 | + ); |
| 59 | + |
| 60 | + return Command::FAILURE; |
| 61 | + } |
| 62 | + |
| 63 | + $result = json_encode( |
| 64 | + (object)[ |
| 65 | + 'constraint' => $constraint, |
| 66 | + 'versions' => Versions::sort(...$versions), |
| 67 | + 'lowest' => Versions::lowest(...$versions), |
| 68 | + 'highest' => Versions::highest(...$versions), |
| 69 | + ], |
| 70 | + JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT |
| 71 | + ); |
| 72 | + |
| 73 | + $io->writeln($result); |
| 74 | + |
| 75 | + return Command::SUCCESS; |
| 76 | + } |
| 77 | +} |
0 commit comments