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

91 lines
2.4 KiB
PHP

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
class HttpRequest extends Request
{
private string $method = 'GET';
private string $version = '1.1';
private ?string $url = null;
private array $query = [];
private array $headers = [];
public function __construct(array $props)
{
foreach ($props as $prop=>$value) {
if (str_starts_with($prop, 'http.')) {
$this->handleHttpProp(substr($prop,5), $value);
} elseif ($prop == 'url') {
$this->url = $value;
}
}
}
private function handleHttpProp(string $prop, $value)
{
if (str_starts_with($prop, 'query.')) {
$this->query[substr($prop, 6)] = $value;
} elseif (str_starts_with($prop, 'header.')) {
$this->headers[substr($prop, 7)] = $value;
} elseif ($prop === 'method') {
$this->method = strtoupper($value);
} elseif ($prop === 'version') {
$this->version = $value;
} else {
fprintf(STDERR, "Warning: unhandled prop: http.%s (%s)\n", $prop, $value);
}
}
public function getInfo(): array
{
$query = http_build_query($this->query);
$headers = [];
foreach ($this->headers as $k=>$v) {
// Convert to Proper-Case unless UPPERCASE
if ($k !== strtoupper($k))
$k = ucwords($k, '-');
// Build the header
$headers[] = sprintf("<options=bold>%s</>: %s", $k, $v);
}
return [
'protocol' => sprintf("HTTP/%s %s", $this->version, $this->method),
'query' => $this->url . "?" . $query,
'body' => "Empty body"
];
}
public function getHeaders(): array
{
$headers = [];
foreach ($this->headers as $k=>$v) {
// Convert to Proper-Case unless UPPERCASE
if ($k !== strtoupper($k))
$k = ucwords($k, '-');
// Build the header
$headers[$k] = (array)$v;
}
return $headers;
}
public function send(): ?Response
{
$query = http_build_query($this->query);
$url = $this->url . ($query?'?'.$query:'');
$config = [];
$client = new Client($config);
$options = [];
$response = $client->request($this->method, $url, $options);
return $response;
}
}