serverctl/src/Commands/StopCommand.php

71 lines
2.5 KiB
PHP

<?php
namespace NoccyLabs\Serverctl\Commands;
use Exception;
use RuntimeException;
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:"stop", description:"Stop a running service")]
class StopCommand extends Command
{
protected function configure()
{
$this->addOption("all", "A", InputOption::VALUE_NONE, "Stop all services");
$this->addOption("instance", "i", InputOption::VALUE_REQUIRED, "Specify the instance name", "default");
$this->addArgument("service", InputArgument::OPTIONAL, "The service name");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$serviceRegistry = $this->getServiceRegistry();
$containerManager = $this->getContainerManager();
$serviceName = $input->getArgument("service");
$instanceName = $input->getOption("instance");
$stopAll = $input->getOption("all");
if (!($serviceName || $stopAll)) {
$output->writeln("<error>You need to specify a service, or --all</>");
return self::FAILURE;
}
if ($stopAll) {
$services = $containerManager->getRunningServices();
foreach ($services as $service) {
$output->write("Stopping...\r");
try {
$containerManager->stopService($service['service'], $service['instance']);
$output->writeln("Stopped service <fg=cyan>".$service['service']['name']."</>[<fg=cyan>".$service['instance']."</>]");
} catch (RuntimeException $e) {
$output->writeln("<error>".$e->getMessage()."</>");
}
}
return self::SUCCESS;
}
$serviceInfo = $serviceRegistry->findServiceByName($serviceName);
if (!$serviceInfo) {
$output->writeln("<error>No such service in registry</>");
return self::FAILURE;
}
$output->write("Stopping...\r");
try {
$containerManager->stopService($serviceInfo, $instanceName);
$output->writeln("Stopped service <fg=cyan>{$serviceName}</>[<fg=cyan>{$instanceName}</>]");
} catch (RuntimeException $e) {
$output->writeln("<error>".$e->getMessage()."</>");
return self::FAILURE;
}
return self::SUCCESS;
}
}