Compare commits

..

7 commits

Author SHA1 Message Date
89a8c04104
feat: add support for OPTIONS requests (#13)
* feat: add support for OPTIONS requests

* feat(doc): add OPTIONS ref. to README
2024-04-06 14:55:04 +00:00
1ed38a8c3d
fix: remove debug line (#12) 2024-04-03 14:12:35 +00:00
6e35a3f7d8
fix: don't set content-type header with no request body (#11) 2024-04-03 14:06:39 +00:00
b029c874df
feat: allow empty args to methods with post bodies (#10) 2024-04-02 15:46:47 +00:00
0110ac1c04
fix: params not sent with http requests (#9) 2024-04-02 12:02:36 +00:00
b33a0e4979
fix: property access before initialization bug (#8) 2024-03-20 12:11:15 +00:00
25b5e2dad1
feat: return Response object from chainable request methods
* feat: add Response object

* wip: 2023-10-02T11:22:18+0200 (1696238538)

* fix: Response from arguments or array

* fix: refactor methods

* feat: add method chaining

* wip: 2024-03-18T11:52:20+0100 (1710759140)

* wip: 2024-03-19T16:51:47+0100 (1710863507)

* feat(doc): update README
2024-03-19 16:16:57 +00:00
5 changed files with 284 additions and 215 deletions

216
README.md
View file

@ -1,91 +1,155 @@
# Reflect API client for PHP # Reflect API client for PHP
Make requests to an API built using the [Reflect API](https://github.com/VictorWesterlund/reflect) framework over HTTP or UNIX sockets. This program comes with both an extendable/instantiable class that you can integrate with existing PHP code, or as a stand-alone CLI which can be run by itself or UNIX piped into other programs. Make requests from a PHP application to an API built with the [Reflect API framework](https://github.com/VictorWesterlund/reflect).
--- ## Installation
Make a request with `Client->call()`. It will always return the response as an array of length 2.
- The first value is the HTTP-equivalent response code.
- The second value is the response body
```php
$client = new Reflect\Client("<API URL or path to UNIX socket>", "<API key (optional)>");
$client->call("foo", Reflect\Method::GET); // (array) [200, "bar"]
$client->call("foo", Reflect\Method::POST, [
"foo" => "bar"
]); // (array) [201, "Created"]
// etc..
```
## How to use
Requires PHP 8.1 or newer, and of course a Reflect API endpoint.
1. **Install with composer** 1. **Install with composer**
```
composer require reflect/client
```
2. **Initialize the class**
```php
require_once "/vendor/autoload.php";
$client = new Reflect\Client("<API URL or path to UNIX socket>", "<API key (optional)>");
```
3. **Make API request**
Use the `call()` method to perform a request
```php
$client->call("foo?bar=baz", Reflect\Method::GET);
```
Argument index|Type|Required|Description
--|--|--|--
0|String|Yes|Fully qualified pathname and query params of the endpoint to call
1|Method\|string|Yes|A supported [Reflect HTTP method](https://github.com/VictorWesterlund/reflect/wiki/Supported-technologies#http-request-methods) (eg. `Method::GET`) or a string represnetation of a supported method (eg. "GET")
2|Array|No|An optional indexed, associative, or multidimensional array that will be sent as the request body as `Content-Type: application/json`
The `call()` function will return an array of length 2 wil the following information
Index|Type|Description
--|--|--
0|Int|HTTP-equivalent response code (eg. `200` or `404`)
1|String/Array|Contains the response body as either a string, or array if the response `Content-Type` header is `application/json`
## How to use (CLI)
You can also run this from the command line with
``` ```
php client <socket_file> <endpoint> <http_method> [payload] composer require reflect/client
``` ```
and it will return a serialized JSON array with the same structure as described in the `Client->call()` return. 2. **`use` in your PHP code**
```php
use Reflect\Client;
*Example* $client = new Client(string $api_base_url, ?string $api_key, ?bool $verify_peer = true);
```sh
php client "/run/reflect.sock" "foo?bar=biz" "POST" "[\"foo\" => \"bar\"]" # (string) [201, \"Created\"]
``` ```
--- ## Making API calls
Requires PHP CLI 8.1 or greater, and of course a Reflect API endpoint. Start by initializing the `Client` with a base URL to the API, and with an optional API key.
1. **Clone repo** ```php
use Reflect\Client;
use Reflect\Method;
``` $client = new Client("https://api.example.com", "MyApiKey");
git clone https://github.com/victorwesterlund/reflect-client-php ```
```
2. **Run from command line**
``` ### Defining an endpoint
// From the root directory of this project
php client <url_or_socket_file_path> <endpoint> <http_method> [payload] Start a new API call by chaining the `call()` method and passing it an endpoint string
```
```php
Client->call(string $endpoint): self
```
Example:
```php
$client->call("my/endpoint");
```
### (Optional) Search Parameters
Pass an associative array of keys and values to `params()`, and chain it anywhere before a `get()`, `patch()`, `put()`, `post()`, or `delete()` request to set search (`$_GET`) parameters for the current request.
```php
Client->params(?array $params = null): self
```
Example:
```php
// https://api.example.com/my/endpoint?key1=value1&key2=value2
$client->call("my/endpoint")
->params([
"key1" => "value1",
"key2" => "value2"
]);
```
### `GET` Request
Make a `GET` request by chaining `get()` at the end of a method chain. This method will return a `Reflect\Response` object.
```php
Client->get(): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint")->params(["foo" => "bar"])->get();
```
### `POST` Request
Make a `POST` request by chaining `post()` at the end of a method chain. This method will return a `Reflect\Response` object.
Pass `post()` a stringifiable associative array of key, value pairs to be sent as an `application/json`-encoded request body to the endpoint.
```php
Client->post(array $payload): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint")->params(["foo" => "bar"])->post(["baz" => "qux"]);
```
### `PATCH` Request
Make a `PATCH` request by chaining `patch()` at the end of a method chain. This method will return a `Reflect\Response` object.
Pass `patch()` a stringifiable associative array of key, value pairs to be sent as an `application/json`-encoded request body to the endpoint.
```php
Client->patch(array $payload): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint")->params(["foo" => "bar"])->patch(["baz" => "qux"]);
```
### `PUT` Request
Make a `PUT` request by chaining `put()` at the end of a method chain. This method will return a `Reflect\Response` object.
Pass `put()` a stringifiable associative array of key, value pairs to be sent as an `application/json`-encoded request body to the endpoint.
```php
Client->put(array $payload): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint")->params(["foo" => "bar"])->put(["baz" => "qux"]);
```
### `DELETE` Request
Make a `DELETE` request by chaining `delete()` at the end of a method chain. This method will return a `Reflect\Response` object.
Pass `delete()` an optional stringifiable associative array of key, value pairs to be sent as an `application/json`-encoded request body to the endpoint.
```php
Client->delete(?array $payload = null): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint")->params(["foo" => "bar"])->delete();
```
### `OPTIONS` Request
Make an `OPTIONS` request by chaining `options()` at the end of a method chain. This method will return a `Reflect\Response` object.
Use this method to query Reflect for available request methods.
```php
Client->options(): Reflect\Response;
```
Example:
```php
$client->call("my/endpoint"))->options();
```

32
client
View file

@ -1,32 +0,0 @@
<?php
use \Reflect\Client;
use \Reflect\Method;
use \Reflect\Connection;
if (php_sapi_name() !== "cli") {
die("Must be run from command line\n");
}
require_once __DIR__ . "/src/Reflect/Client.php";
// Require 3 to 4 arguments
if ($argc < 4 || $argc > 4) {
$arglen = $argc - 1;
exit("Expected 3 to 4 arguments (got ${arglen}): <reflect_socket_path> <endpoint> <http_method> [payload]\n");
}
// Connect to the socket server
$client = new Client($argv[1], null, Connection::AF_UNIX);
// Get endpoint, method, and optional payload
$args = $argv;
array_shift($args);
array_shift($args);
// Restore enum from argument
$args[1] = Method::from(strtoupper($args[1]));
// Call endpoint and echo result
$call = $client->call(...$args);
echo json_encode($call) . "\n";

View file

@ -2,148 +2,142 @@
namespace Reflect; namespace Reflect;
// Allowed HTTP verbs use Reflect\Method;
enum Method: string { use Reflect\Response;
case GET = "GET";
case POST = "POST";
case PUT = "PUT";
case DELETE = "DELETE";
case PATCH = "PATCH";
case OPTIONS = "OPTIONS";
}
// Supported connection methods require_once "Method.php";
enum Connection { require_once "Response.php";
case HTTP;
case AF_UNIX;
}
class Client { class Client {
// API key string private string $params;
private ?string $key;
// Connection method
private Connection $con;
// Request endpoitn string
private string $endpoint; private string $endpoint;
private array $headers = [];
private ?array $payload = null;
// Socket instance protected ?string $key;
private Socket|false $socket = false; protected string $base_url;
// Flag: Allow unverified SSL certificates for HTTPS protected bool $https_verify_peer;
private bool $https_peer_verify = true;
public function __construct(string $base_url, string $key = null, bool $verify_peer = true) {
// Use this HTTP method if no method specified to call() // Set optional API key and Authorization header
const HTTP_DEFAULT_METHOD = Method::GET;
// The amount of bytes to read for each chunk from socket
const SOCKET_READ_BYTES = 2048;
public function __construct(string $endpoint, string $key = null, Connection $con = null, bool $https_peer_verify = true) {
$this->con = $con ?: $this::resolve_connection($endpoint);
$this->endpoint = $endpoint;
$this->key = $key; $this->key = $key;
if ($this->con === Connection::AF_UNIX) { // Append tailing "/" if absent
// Connect to Reflect UNIX socket $this->base_url = substr($base_url, -1) === "/" ? $base_url : $base_url . "/";
$this->_socket = socket_create(AF_UNIX, SOCK_STREAM, 0); // Flag which enables or disables SSL peer validation (for self-signed certificates)
$conn = socket_connect($this->_socket, $this->endpoint); $this->https_verify_peer = $verify_peer;
} else if ($this->con === Connection::HTTP) {
// Append tailing "/" for HTTP if absent
$this->endpoint = substr($this->endpoint, -1) === "/" ? $this->endpoint : $this->endpoint . "/";
// Flag which enables or disables SSL peer validation (for self-signed certificates)
$this->https_peer_verify = $https_peer_verify;
}
} }
// Resolve connection type from endpoint string. // Convert assoc array to URL-encoded string or empty string if array is empty
// If the string is a valid URL we will treat it as HTTP otherwise we will assume it's a path on disk to a UNIX socket file. private static function get_params(array $params): string {
private static function resolve_connection(string $endpoint): Connection { return !empty($params) ? "?" . http_build_query($params) : "";
return filter_var($endpoint, FILTER_VALIDATE_URL)
? Connection::HTTP
: Connection::AF_UNIX;
} }
// Attempt to resolve Method from backed enum string, or return default // ----
private static function resolve_method(Method|string $method): Method {
return ($method instanceof Method)
? $method
: Method::tryFrom($method) ?? (__CLASS__)::HTTP_DEFAULT_METHOD;
}
// Construct stream_context_create() compatible header string // Construct stream_context_create() compatible header string
private function http_headers(): string { private function get_headers(): string {
$headers = ["Content-Type: application/json"]; // Set Authorization header if an API key is used
if ($this->key) {
// Append Authentication header if API key is provided $this->headers["Authorization"] = "Bearer {$this->key}";
if (!empty($this->key)) {
$headers[] = "Authorization: Bearer {$this->key}";
} }
// Append new line chars to each header // Construct HTTP headers string from array
$headers = array_map(fn($header): string => $header . "\r\n", $headers); $headers = array_map(fn(string $k, string $v): string => "{$k}: {$v}\r\n", array_keys($this->headers), array_values($this->headers));
return implode("", $headers); return implode("", $headers);
} }
// Make request and return response over HTTP // Make request and return response over HTTP
private function http_call(string $endpoint, Method|string $method = (__CLASS__)::HTTP_DEFAULT_METHOD, array $payload = null): array { private function http_call(Method $method): array {
// Resolve string to enum $context = stream_context_create([
$method = $this::resolve_method($method);
// Remove leading "/" if present, as it's already present in $this->endpoint
$endpoint = substr($endpoint, 0, 1) !== "/" ? $endpoint : substr($endpoint, 1, strlen($endpoint) - 1);
$data = stream_context_create([
"http" => [ "http" => [
"header" => $this->http_headers(), "header" => $this->get_headers(),
"method" => $method->value, "method" => $method->name,
"ignore_errors" => true, "ignore_errors" => true,
"content" => !empty($payload) ? json_encode($payload) : "" "content" => !empty($this->payload) ? json_encode($this->payload) : ""
], ],
"ssl" => [ "ssl" => [
"verify_peer" => $this->https_peer_verify, "verify_peer" => $this->https_verify_peer,
"verify_peer_name" => $this->https_peer_verify, "verify_peer_name" => $this->https_verify_peer,
"allow_self_signed" => !$this->https_peer_verify "allow_self_signed" => !$this->https_verify_peer
] ]
]); ]);
$resp = file_get_contents($this->endpoint . $endpoint, false, $data); $resp = file_get_contents(implode("", [$this->base_url, $this->endpoint, $this->params]), false, $context);
// Get HTTP response code from $http_response_header which materializes out of thin air after file_get_contents(). // Get HTTP response code from $http_response_header which materializes out of thin air after file_get_contents().
// The first header line and second word will contain the status code. // The first header line and second word will contain the status code.
$resp_code = (int) explode(" ", $http_response_header[0])[1]; $resp_code = (int) explode(" ", $http_response_header[0])[1];
// Return response as [<http_status_code>, <resp_body_assoc_array>] // Return response as [<resp_body_assoc_array>, <http_status_code>]
return [$resp_code, json_decode($resp, true)]; return [$resp, $resp_code];
} }
// Make request and return response over socket // Set request body to be JSON-stringified
private function socket_txn(string $payload): string { private function set_request_body(?array $payload = null): self {
$tx = socket_write($this->_socket, $payload, strlen($payload)); // Unset request body if no payload defined
$rx = socket_read($this->_socket, $this::SOCKET_READ_BYTES); if (empty($payload)) {
$this->payload = null;
if (!$tx || !$rx) { return $this;
throw new \Error("Failed to complete transaction");
} }
return $rx; $this->headers["Content-Type"] = "application/json";
$this->payload = $payload;
return $this;
} }
// Call a Reflect endpoint and return response as assoc array // ----
public function call(string $endpoint, Method|string $method = (__CLASS__)::HTTP_DEFAULT_METHOD, array $payload = null): array {
// Resolve string to enum
$method = $this::resolve_method($method);
// Call endpoint over UNIX socket // Construct URL search parameters from array if set
if ($this->con === Connection::AF_UNIX) { public function params(?array $params = null): self {
// Return response as assoc array $this->params = !empty($params) ? self::get_params($params) : "";
return json_decode($this->socket_txn( return $this;
// Send request as stringified JSON
json_encode([
$endpoint,
$method->value,
$payload
])
), true);
}
// Call endpoint over HTTP
return $this->http_call(...func_get_args());
} }
}
// Create a new call to an endpoint
public function call(string $endpoint): self {
// Remove leading "/" if present, as it's already present in $this->base_url
$this->endpoint = substr($endpoint, 0, 1) !== "/"
? $endpoint
: substr($endpoint, 1, strlen($endpoint) - 1);
// Reset initial values
$this->params();
$this->headers = [];
$this->set_request_body();
return $this;
}
// ----
// Make a GET request to endpoint with optional search parameters
public function get(): Response {
return new Response(...$this->http_call(Method::GET));
}
public function patch(?array $payload = []): Response {
$this->set_request_body($payload);
return new Response(...$this->http_call(Method::PATCH));
}
public function put(?array $payload = []): Response {
$this->set_request_body($payload);
return new Response(...$this->http_call(Method::PUT));
}
public function post(?array $payload = []): Response {
$this->set_request_body($payload);
return new Response(...$this->http_call(Method::POST));
}
public function delete(?array $payload = []): Response {
$this->set_request_body($payload);
return new Response(...$this->http_call(Method::DELETE));
}
public function options(): Response {
return new Response(...$this->http_call(Method::OPTIONS));
}
}

13
src/Reflect/Method.php Normal file
View file

@ -0,0 +1,13 @@
<?php
namespace Reflect;
// Allowed HTTP verbs
enum Method {
case GET;
case POST;
case PUT;
case DELETE;
case PATCH;
case OPTIONS;
}

30
src/Reflect/Response.php Normal file
View file

@ -0,0 +1,30 @@
<?php
namespace Reflect;
class Response {
public int $code;
public bool $ok = false;
private mixed $body;
public function __construct(string|array $resp, int $code = 200) {
// Get response body from array or directly from string
$this->body = is_array($resp) ? $resp[0] : $resp;
// Set response code from array or with method argument
$this->code = is_array($resp) ? (int) $resp[1] : $code;
// Response code is within the Success range
$this->ok = $this->code >= 200 && $this->code < 300;
}
// Parse JSON from response body and return as PHP array
public function json(bool $assoc = true): array {
return json_decode($this->body, $assoc);
}
// Return response body as-is
public function output() {
return $this->body;
}
}