|
| 1 | +<?php |
| 2 | +namespace PHPJava\Console\Commands\JVM; |
| 3 | + |
| 4 | +use PHPJava\Core\JavaArchive; |
| 5 | +use PHPJava\Core\JavaClass; |
| 6 | +use PHPJava\Core\JVM\Parameters\GlobalOptions; |
| 7 | +use PHPJava\Core\Stream\Reader\FileReader; |
| 8 | +use Symfony\Component\Console\Command\Command; |
| 9 | +use Symfony\Component\Console\Input\InputArgument; |
| 10 | +use Symfony\Component\Console\Input\InputDefinition; |
| 11 | +use Symfony\Component\Console\Input\InputInterface; |
| 12 | +use Symfony\Component\Console\Input\InputOption; |
| 13 | +use Symfony\Component\Console\Output\OutputInterface; |
| 14 | + |
| 15 | +class RunCommand extends Command |
| 16 | +{ |
| 17 | + protected static $defaultName = 'jvm:run'; |
| 18 | + |
| 19 | + protected function configure() |
| 20 | + { |
| 21 | + $this |
| 22 | + ->addArgument( |
| 23 | + 'file', |
| 24 | + InputArgument::REQUIRED, |
| 25 | + 'Specify to run [jar|class] file.' |
| 26 | + ) |
| 27 | + ->addArgument( |
| 28 | + 'parameters', |
| 29 | + InputArgument::OPTIONAL | InputArgument::IS_ARRAY, |
| 30 | + 'Specify parameters to pass for entrypoint.' |
| 31 | + ) |
| 32 | + ->addOption( |
| 33 | + 'settings', |
| 34 | + 's', |
| 35 | + InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, |
| 36 | + 'Set option settings.' |
| 37 | + ) |
| 38 | + ->addOption( |
| 39 | + 'mode', |
| 40 | + 'm', |
| 41 | + InputOption::VALUE_OPTIONAL, |
| 42 | + 'Set run mode [jar|class]. Default is class.' |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 47 | + { |
| 48 | + $settings = $input->getOption('settings') ?? []; |
| 49 | + $mode = strtolower($input->getOption('mode') ?? 'class'); |
| 50 | + $file = $input->getArgument('file'); |
| 51 | + $parameters = $input->getArgument('parameters'); |
| 52 | + |
| 53 | + // Set global options |
| 54 | + GlobalOptions::set($settings); |
| 55 | + |
| 56 | + if ($mode === 'jar') { |
| 57 | + return $this->runJar($file, $parameters); |
| 58 | + } elseif ($mode === 'class') { |
| 59 | + return $this->runClass($file, $parameters); |
| 60 | + } |
| 61 | + |
| 62 | + $output->writeln( |
| 63 | + '<error>Unable to run `' . $mode . '` mode.</error>' |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + private function runJar(string $file, array $parameters) |
| 68 | + { |
| 69 | + $jar = new JavaArchive($file); |
| 70 | + $jar->execute( |
| 71 | + $parameters |
| 72 | + ); |
| 73 | + } |
| 74 | + |
| 75 | + private function runClass(string $file, array $parameters) |
| 76 | + { |
| 77 | + $class = new JavaClass( |
| 78 | + new FileReader($file) |
| 79 | + ); |
| 80 | + $class |
| 81 | + ->getInvoker() |
| 82 | + ->getStatic() |
| 83 | + ->getMethods() |
| 84 | + ->call( |
| 85 | + 'main', |
| 86 | + $parameters |
| 87 | + ); |
| 88 | + } |
| 89 | +} |
0 commit comments