php-spark/plugins/com.noccy.apiclient/sparkplug.php

128 lines
3.3 KiB
PHP
Raw Permalink Normal View History

<?php // "name":"Call on web APIs", "author":"Noccy"
namespace SparkPlug\Com\Noccy\ApiClient;
use SparkPlug;
use SparkPlug\Com\Noccy\ApiClient\Log\RequestLog;
use SparkPlug\Com\Noccy\ApiClient\Log\LogIterator;
class ApiClientPlugin extends SparkPlug
{
private array $catalogs = [];
private array $profiles = [];
public function load()
{
register_command(new Commands\ApiCatalogCommand());
register_command(new Commands\ApiRequestCommand());
register_command(new Commands\ApiProfileCommand());
register_command(new Commands\ApiLogsCommand());
}
private function loadCatalogs()
{
$env = get_environment();
$catalogDir = $env->getConfigDirectory() . "/api/catalogs";
if (file_exists($catalogDir)) {
$catalogFiles = glob($catalogDir."/*.json");
foreach ($catalogFiles as $catalogFile) {
$name = basename($catalogFile, ".json");
$this->catalogs[$name] = Api\Catalog::createFromFile($catalogFile);
}
}
}
private function loadProfiles()
{
$env = get_environment();
$catalogDir = $env->getConfigDirectory() . "/api/profiles";
if (file_exists($catalogDir)) {
$catalogFiles = glob($catalogDir."/*.json");
foreach ($catalogFiles as $catalogFile) {
}
}
}
public function createCatalog(string $name): ?Api\Catalog
{
return null;
}
public function saveCatalog(Api\Catalog $catalog)
{
$env = get_environment();
$catalogDir = $env->getConfigDirectory() . "/api/catalogs";
$catalogFile = $catalogDir . "/" . $catalog->getName() . ".json";
if (!is_dir($catalogDir)) {
mkdir($catalogDir, 0777, true);
}
file_put_contents($catalogFile."~", json_encode($catalog, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
rename($catalogFile."~", $catalogFile);
}
public function deleteCatalog(string $name)
{
}
public function getCatalog(string $name): ?Api\Catalog
{
if (empty($this->catalogs)) $this->loadCatalogs();
return $this->catalogs[$name]??null;
}
public function getCatalogNames(): array
{
if (empty($this->catalogs)) $this->loadCatalogs();
return array_keys($this->catalogs);
}
public function saveProfile(string $name, Api\Profile $profile)
{
}
public function deleteProfile(string $name)
{
}
public function getProfile(string $name): ?Api\Profile
{
if (empty($this->profiles)) $this->loadProfiles();
return null;
}
public function getProfileNames(): array
{
if (empty($this->profiles)) $this->loadProfiles();
return array_keys($this->profiles);
}
public function getRequestLog(string $name): RequestLog
{
$env = get_environment();
$logsDir = $env->getConfigDirectory() . "/api/logs/";
$log = new RequestLog($logsDir.$name.".json");
return $log;
}
public function getLogIterator(string $name): LogIterator
{
$env = get_environment();
$logsDir = $env->getConfigDirectory() . "/api/logs/";
$iter = new LogIterator($logsDir.$name.".json");
return $iter;
}
}
register_plugin("com.noccy.apiclient", new ApiClientPlugin);