serverctl/src/Commands/ExecCommand.php

61 lines
2.4 KiB
PHP

<?php
namespace NoccyLabs\Serverctl\Commands;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name:"exec", description:"Execute a shell command or script in the service")]
class ExecCommand extends Command
{
protected function configure()
{
$this->addOption("instance", "i", InputOption::VALUE_REQUIRED, "Specify the instance name", "default");
$this->addOption("script", "s", InputOption::VALUE_NONE, "The command is a script (use 'list' for list)");
$this->addArgument("service", InputArgument::REQUIRED, "The service name");
$this->addArgument("execute", InputArgument::REQUIRED, "The command or script to execute");
$this->addArgument("arguments", InputArgument::IS_ARRAY, "Arguments");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$serviceRegistry = $this->getServiceRegistry();
$containerManager = $this->getContainerManager();
$instanceName = $input->getOption("instance");
$serviceName = $input->getArgument("service");
$command = $input->getArgument("execute");
$serviceInfo = $serviceRegistry->findServiceByName($serviceName);
if ($command == "list") {
$scripts = (array)($serviceInfo['scripts']??[]);
$output->writeln("Available scripts:");
foreach ($scripts as $script=>$meta) {
$output->writeln(sprintf(" <comment>%s</> - <info>%s</>", $script, $meta['info']??"?"));
}
return self::SUCCESS;
} elseif ($input->getOption("script")) {
$script = $serviceInfo['scripts'][$command]['execute']??null;
if (!$script) {
$output->writeln("<error>No such script</>");
return self::FAILURE;
}
$cmdl = [ is_array($script)?join("; ", $script):$script ];
$containerManager->execute($serviceInfo, $instanceName, $cmdl);
} else {
$cmdl = [ $input->getArgument("execute") ];
array_push($cmdl, ...$input->getArgument("arguments"));
$containerManager->execute($serviceInfo, $instanceName, $cmdl);
}
return self::SUCCESS;
}
}