|
| 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 | + |
| 14 | +#[AsCommand( |
| 15 | + name: 'constraint', |
| 16 | + description: 'List PHP versions that satisfy the given constraint', |
| 17 | +)] |
| 18 | +class ConstraintCommand extends Command |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private readonly MatrixFactory $matrixFactory = new MatrixFactory, |
| 22 | + ) { |
| 23 | + parent::__construct(); |
| 24 | + } |
| 25 | + |
| 26 | + public function __invoke( |
| 27 | + SymfonyStyle $io, |
| 28 | + #[Argument(description: 'The version constraint.')] |
| 29 | + string $constraint, |
| 30 | + #[SourceOption] |
| 31 | + string $source = Source::Auto->value, |
| 32 | + #[ModeOption] |
| 33 | + string $mode = Mode::MinorOnly->value, |
| 34 | + ): int { |
| 35 | + try { |
| 36 | + $matrix = $this->matrixFactory->make( |
| 37 | + Source::fromValue($source), |
| 38 | + Mode::fromValue($mode), |
| 39 | + ); |
| 40 | + |
| 41 | + $versions = $matrix->satisfiedBy($constraint); |
| 42 | + if (empty($versions)) { |
| 43 | + throw new RuntimeException( |
| 44 | + sprintf("Error! No PHP versions could satisfy the constraint '%s'.", $constraint) |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + $result = json_encode( |
| 49 | + (object)[ |
| 50 | + 'constraint' => $constraint, |
| 51 | + 'versions' => Versions::sort(...$versions), |
| 52 | + 'lowest' => Versions::lowest(...$versions), |
| 53 | + 'highest' => Versions::highest(...$versions), |
| 54 | + ], |
| 55 | + JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT |
| 56 | + ); |
| 57 | + |
| 58 | + $io->writeln($result); |
| 59 | + |
| 60 | + return Command::SUCCESS; |
| 61 | + } catch (\UnexpectedValueException $e) { |
| 62 | + $io |
| 63 | + ->getErrorStyle() |
| 64 | + ->error( |
| 65 | + $e->getMessage(), |
| 66 | + ); |
| 67 | + |
| 68 | + return Command::FAILURE; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments