php-spark/plugins/com.noccy.apiclient/Commands/ApiCatalogCommand.php

92 lines
3.7 KiB
PHP

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Commands;
use Spark\Commands\Command;
use SparkPlug;
use SparkPlug\Com\Noccy\ApiClient\Api\Catalog;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ApiCatalogCommand extends Command
{
protected function configure()
{
$this->setName("api:catalog")
->setDescription("Manage the API catalogs")
->addOption("create", "c", InputOption::VALUE_REQUIRED, "Create a new catalog")
->addOption("remove", "r", InputOption::VALUE_REQUIRED, "Remove a catalog")
->addOption("set-props", null, InputOption::VALUE_REQUIRED, "Apply properties to a catalog")
->addArgument("properties", InputArgument::IS_ARRAY, "Default properties for the catalog")
->addOption("list", null, InputOption::VALUE_NONE, "Only list catalogs, not methods")
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$api = get_plugin('com.noccy.apiclient');
$list = $input->getOption("list");
$dest = get_environment()->getConfigDirectory() . "/api/catalogs";
if ($create = $input->getOption("create")) {
if (file_exists($dest."/".$create.".json")) {
$output->writeln("<error>Catalog {$create} already exists!</>");
return Command::FAILURE;
}
$catalog = new Catalog([
'catalog' => [
'name' => $create
]
]);
file_put_contents($dest."/".$create.".json", json_encode($catalog, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
$output->writeln("<info>Created new catalog {$create}</>");
return Command::SUCCESS;
}
if ($remove = $input->getOption("remove")) {
if (!file_exists($dest."/".$remove.".json")) {
$output->writeln("<error>Catalog {$remove} does not exist!</>");
return Command::FAILURE;
}
unlink($dest."/".$remove.".json");
$output->writeln("<info>Removed catalog {$remove}</>");
return Command::SUCCESS;
}
if ($setprops = $input->getOption("set-props")) {
$proparr = [];
$props = $input->getArgument("properties");
foreach ($props as $str) {
if (!str_contains($str,"=")) {
$output->writeln("<error>Ignoring parameter argument '{$str}'</>");
} else {
[$k,$v] = explode("=",$str,2);
$proparr[$k] = $v;
}
}
$catalog = $api->getCatalog($setprops);
$catalog->applyProperties($proparr);
$api->saveCatalog($catalog);
$output->writeln("<info>Updated properties on catalog {$setprops}</>");
return Command::SUCCESS;
}
$catalogs = $api->getCatalogNames();
foreach ($catalogs as $catalog) {
$c = $api->getCatalog($catalog);
if ($list) {
$output->writeln($catalog);
} else {
$output->writeln("\u{25e9} <options=bold>{$catalog}</>: <fg=gray>{$c->getInfo()}</>");
$ms = $c->getMethods();
foreach ($ms as $name=>$m) {
$last = ($m === end($ms));
$output->writeln(($last?"\u{2514}\u{2500}":"\u{251c}\u{2500}")."\u{25a2} {$catalog}.{$name}: <info>{$m->getInfo()}</>");
}
}
}
return Command::SUCCESS;
}
}