php-spark/plugins/com.noccy.apiclient/sparkplug.php
Christopher Vagnetoft 30dfd4889b Misc fixes and improvements
* Added request logging to com.noccy.apiclient
* Added plugin com.noccy.watcher
* Added pipe command and filter support
* Fixes and stubs
2021-12-14 23:01:25 +01:00

119 lines
3.0 KiB
PHP

<?php // "name":"Call on web APIs", "author":"Noccy"
namespace SparkPlug\Com\Noccy\ApiClient;
use SparkPlug;
use SparkPlug\Com\Noccy\ApiClient\Log\RequestLog;
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;
}
}
register_plugin("com.noccy.apiclient", new ApiClientPlugin);