php-spark/plugins/com.noccy.apiclient/Log/RequestData.php

76 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Log;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface;
use SparkPlug\Com\Noccy\ApiClient\Log\RequestData as LogRequestData;
use SparkPlug\Com\Noccy\ApiClient\Request\Request;
class RequestData implements JsonSerializable
{
private ?string $method = null;
private array $params = [];
private ?int $timestamp = null;
private ?string $requestUrl = null;
private array $requestInfo = [];
private array $requestHeaders = [];
private ?string $responseBody = null;
private ?int $responseStatus = null;
private array $responseHeaders = [];
public static function fromRequestResponse(Request $request, ResponseInterface $response, ?string $method=null, array $params=[]): RequestData
{
$rd = new RequestData();
$rd->method = $method;
$rd->params = $params;
$rd->timestamp = time();
$rd->requestInfo = $request->getInfo();
$rd->requestHeaders = $request->getHeaders();
$rd->responseBody = (string)$response->getBody();
$rd->responseHeaders = $response->getHeaders();
return $rd;
}
public static function fromArray(array $array): RequestData
{
$rd = new RequestData();
$rd->method = $array['method']??'n/a';
$rd->params = $array['params']??[];
$rd->timestamp = $array['request']['timestamp']??null;
$rd->requestInfo = $array['request']['info']??[];
$rd->requestHeaders = $array['request']['headers']??[];
$rd->responseBody = $array['response']['body']??null;
$rd->responseHeaders = $array['response']['headers']??[];
return $rd;
}
public function jsonSerialize(): mixed
{
return [
'method' => $this->method,
'params' => $this->params,
'request' => [
'url' => $this->requestUrl,
'timestamp' => $this->timestamp,
'info' => $this->requestInfo,
'headers' => $this->requestHeaders,
],
'response' => [
'status' => $this->responseStatus,
'headers' => $this->responseHeaders,
'body' => $this->responseBody,
]
];
}
}