php-spark/plugins/com.noccy.apiclient/Request/RequestBuilder.php

100 lines
2.4 KiB
PHP

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Request;
use SparkPlug\Com\Noccy\ApiClient\Api\Catalog;
use SparkPlug\Com\Noccy\ApiClient\Api\Method;
use SparkPlug\Com\Noccy\ApiClient\Api\Profile;
class RequestBuilder
{
public static $Protocols = [
'http' => HttpRequest::class,
'websocket' => WebSocketRequest::class,
'jsonrpc' => JsonRpcRequest::class,
];
private ?Catalog $catalog = null;
private ?Method $method = null;
private ?Profile $profile = null;
private array $props = [];
public function setCatalog(?Catalog $catalog)
{
$this->catalog = $catalog;
return $this;
}
public function setMethod(?Method $method)
{
$this->method = $method;
return $this;
}
public function setProfile(?Profile $profile)
{
$this->profile = $profile;
return $this;
}
public function setProperties(array $properties)
{
$this->props = $properties;
}
public function addProperties(array $properties)
{
$this->props = array_merge(
$this->props,
$properties
);
}
private function buildProperties()
{
$props = [];
if ($this->catalog) {
$add = $this->catalog->getProperties();
$props = array_merge($props, $add);
}
if ($this->method) {
$add = $this->method->getProperties();
$props = array_merge($props, $add);
}
if ($this->profile) {
$add = $this->profile->getProperties();
$props = array_merge($props, $add);
}
$props = array_merge($props, $this->props);
$props = array_filter($props);
return $props;
}
public function getCalculatedProperty(string $name)
{
$props = $this->buildProperties();
return $props[$name] ?? null;
}
public function getRequest(): Request
{
$props = $this->buildProperties();
$protocol = $props['protocol']??'http';
if (!$handler = self::$Protocols[$protocol]??null) {
throw new \Exception("Invalid protocol for request: {$protocol}");
}
$base = $props['urlbase']??null;
$url = $props['url']??null;
if ($base) {
$props['url'] = $base . $url;
}
$request = new $handler($props);
return $request;
}
}