Skip to content

Instantly share code, notes, and snippets.

@adamwathan

adamwathan/0.md Secret

Last active October 15, 2021 00:17
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save adamwathan/e7023ff8fe84168b6e26744bab655cae to your computer and use it in GitHub Desktop.
Save adamwathan/e7023ff8fe84168b6e26744bab655cae to your computer and use it in GitHub Desktop.
Zttp

Example usage:

$jsonResult = Zttp::withHeaders(['Authorization' => 'Bearer '.$key])->post($endpoint, $payload)->json();
<?php
namespace App;
class Zttp
{
static function __callStatic($method, $args)
{
return ZttpRequest::new()->{$method}(...$args);
}
}
class ZttpRequest
{
function __construct()
{
$this->headers = [];
$this->bodyFormat = 'json';
}
static function new()
{
return new self;
}
function asJson()
{
$this->bodyFormat = 'json';
return $this->contentType('application/json');
}
function asFormParams()
{
$this->bodyFormat = 'form_params';
return $this->contentType('application/x-www-form-urlencoded');
}
function contentType($contentType)
{
return $this->withHeaders(['Content-Type' => $contentType]);
}
function accept($header)
{
return $this->withHeaders(['Accept' => $header]);
}
function withHeaders($headers)
{
return tap($this, function ($request) use ($headers) {
$this->headers = array_merge($this->headers, $headers);
});
}
function get($url, $queryParams = [])
{
return $this->_send('GET', $url, [
'query' => $queryParams,
]);
}
function post($url, $params = [])
{
return $this->_send('POST', $url, [
$this->bodyFormat => $params,
]);
}
function _send($method, $url, $options)
{
$response = (new \GuzzleHttp\Client)->request($method, $url, array_merge([
'http_errors' => false,
'headers' => $this->headers,
], $options));
return new ZttpResponse($response);
}
}
class ZttpResponse
{
function __construct($response)
{
$this->response = $response;
}
function body()
{
return (string) $this->response->getBody();
}
function json()
{
return json_decode($this->response->getBody(), true);
}
function header($header)
{
return $this->response->getHeaderLine($header);
}
function status()
{
return $this->response->getStatusCode();
}
function isSuccess()
{
return in_array($this->status(), array_merge(range(200, 208), [226]));
}
function isRedirect()
{
return in_array($this->status(), range(300, 308));
}
function __call($method, $args)
{
return $this->response->{$method}(...$args);
}
}
class ZttpException extends \RuntimeException {}
@thecrypticace
Copy link

ZttpException and it's not even used. smh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment