mirror of
https://codeberg.org/reflect/reflect-client-php.git
synced 2025-09-14 10:03:41 +02:00
Compare commits
No commits in common. "master" and "1.0.0" have entirely different histories.
7 changed files with 151 additions and 330 deletions
218
README.md
218
README.md
|
@ -1,155 +1,91 @@
|
||||||
# Reflect API client for PHP
|
# Reflect API UNIX socket client for PHP
|
||||||
|
|
||||||
Make requests from a PHP application to an API built with the [Reflect API framework](https://github.com/VictorWesterlund/reflect).
|
Make requests to endpoints created with the [Reflect API framework](https://github.com/victorwesterlund/reflect) running the same machine.
|
||||||
|
|
||||||
## Installation
|
---
|
||||||
|
|
||||||
|
Make a request with `SocketClient->call()`. It will 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\SocketClient("/path/to/socket");
|
||||||
|
|
||||||
|
$client->call("foo", Method::GET); // (array) [200, "bar"]
|
||||||
|
$client->call("foo", Method::POST, [
|
||||||
|
"foo" => "bar"
|
||||||
|
]); // (array) [201, "Created"]
|
||||||
|
|
||||||
|
// etc..
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to use
|
||||||
|
|
||||||
|
Requires PHP 8.1 or newer, and of course an instance of the [Reflect socket server](https://github.com/VictorWesterlund/reflect/wiki/UNIX-Sockets) running on the same machine.
|
||||||
|
|
||||||
1. **Install with composer**
|
1. **Install with composer**
|
||||||
|
|
||||||
|
```
|
||||||
|
composer require reflect/socket-server
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Initialize the class**
|
||||||
|
|
||||||
|
```php
|
||||||
|
require_once "/vendor/autoload.php";
|
||||||
|
|
||||||
|
$client = new Reflect\SocketClient("/path/to/socket");
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Make API request**
|
||||||
|
|
||||||
|
Use the `call()` method to perform a request
|
||||||
|
|
||||||
|
```php
|
||||||
|
$client->call("foo?bar=baz", Method::GET);
|
||||||
|
```
|
||||||
|
|
||||||
|
Argument index|Type|Required|Description
|
||||||
|
--|--|--|--
|
||||||
|
0|String|Yes|Fully qualified pathname and query params of the endpoint to call
|
||||||
|
1|Method|Yes|A supported [Reflect HTTP method](https://github.com/VictorWesterlund/reflect/wiki/Supported-technologies#http-request-methods) (eg. `Method::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
|
||||||
|
|
||||||
```
|
```
|
||||||
composer require reflect/client
|
php client <socket_file> <endpoint> <http_method> [payload]
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **`use` in your PHP code**
|
and it will return a serialized JSON array with the same structure as described in the `SocketClient->call()` return.
|
||||||
```php
|
|
||||||
use Reflect\Client;
|
|
||||||
|
|
||||||
$client = new Client(string $api_base_url, ?string $api_key, ?bool $verify_peer = true);
|
*Example*
|
||||||
|
```sh
|
||||||
|
php client "/run/reflect.sock" "foo?bar=biz" "POST" "[\"foo\" => \"bar\"]" # (string) [201, \"Created\"]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Making API calls
|
---
|
||||||
|
|
||||||
Start by initializing the `Client` with a base URL to the API, and with an optional API key.
|
Requires PHP CLI 8.1 or greater, and of course an instance of the [Reflect socket server](https://github.com/VictorWesterlund/reflect/wiki/UNIX-Sockets) running on the same machine.
|
||||||
|
|
||||||
```php
|
1. **Clone repo**
|
||||||
use Reflect\Client;
|
|
||||||
use Reflect\Method;
|
|
||||||
|
|
||||||
$client = new Client("https://api.example.com", "MyApiKey");
|
```
|
||||||
```
|
git clone https://github.com/victorwesterlund/reflect-socket-client-php
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Run from command line**
|
||||||
|
|
||||||
### Defining an endpoint
|
```
|
||||||
|
cd reflect-socket-client-php
|
||||||
Start a new API call by chaining the `call()` method and passing it an endpoint string
|
php client <socket_file> <endpoint> <http_method> [payload]
|
||||||
|
```
|
||||||
```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();
|
|
||||||
```
|
|
||||||
|
|
28
client
Normal file
28
client
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
if (php_sapi_name() !== "cli") {
|
||||||
|
die("Must be run from command line\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once __DIR__ . "/src/SocketClient.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 SocketClient($argv[1]);
|
||||||
|
|
||||||
|
// 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";
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "reflect/client",
|
"name": "reflect/socket-client",
|
||||||
"description": "Extendable PHP interface for communicating with Reflect API over HTTP or UNIX sockets",
|
"description": "Extendable PHP interface for communicating with Reflect API over UNIX sockets",
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"license": "GPL-2.0-only",
|
"license": "GPL-2.0-only",
|
||||||
"authors": [
|
"authors": [
|
||||||
|
@ -12,7 +12,7 @@
|
||||||
"minimum-stability": "dev",
|
"minimum-stability": "dev",
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"Reflect\\": "src/Reflect/"
|
"Reflect\\": "src/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"require": {}
|
"require": {}
|
||||||
|
|
|
@ -1,143 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace Reflect;
|
|
||||||
|
|
||||||
use Reflect\Method;
|
|
||||||
use Reflect\Response;
|
|
||||||
|
|
||||||
require_once "Method.php";
|
|
||||||
require_once "Response.php";
|
|
||||||
|
|
||||||
class Client {
|
|
||||||
private string $params;
|
|
||||||
private string $endpoint;
|
|
||||||
private array $headers = [];
|
|
||||||
private ?array $payload = null;
|
|
||||||
|
|
||||||
protected ?string $key;
|
|
||||||
protected string $base_url;
|
|
||||||
protected bool $https_verify_peer;
|
|
||||||
|
|
||||||
public function __construct(string $base_url, string $key = null, bool $verify_peer = true) {
|
|
||||||
// Set optional API key and Authorization header
|
|
||||||
$this->key = $key;
|
|
||||||
|
|
||||||
// Append tailing "/" if absent
|
|
||||||
$this->base_url = substr($base_url, -1) === "/" ? $base_url : $base_url . "/";
|
|
||||||
// Flag which enables or disables SSL peer validation (for self-signed certificates)
|
|
||||||
$this->https_verify_peer = $verify_peer;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert assoc array to URL-encoded string or empty string if array is empty
|
|
||||||
private static function get_params(array $params): string {
|
|
||||||
return !empty($params) ? "?" . http_build_query($params) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----
|
|
||||||
|
|
||||||
// Construct stream_context_create() compatible header string
|
|
||||||
private function get_headers(): string {
|
|
||||||
// Set Authorization header if an API key is used
|
|
||||||
if ($this->key) {
|
|
||||||
$this->headers["Authorization"] = "Bearer {$this->key}";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Construct HTTP headers string from array
|
|
||||||
$headers = array_map(fn(string $k, string $v): string => "{$k}: {$v}\r\n", array_keys($this->headers), array_values($this->headers));
|
|
||||||
return implode("", $headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make request and return response over HTTP
|
|
||||||
private function http_call(Method $method): array {
|
|
||||||
$context = stream_context_create([
|
|
||||||
"http" => [
|
|
||||||
"header" => $this->get_headers(),
|
|
||||||
"method" => $method->name,
|
|
||||||
"ignore_errors" => true,
|
|
||||||
"content" => !empty($this->payload) ? json_encode($this->payload) : ""
|
|
||||||
],
|
|
||||||
"ssl" => [
|
|
||||||
"verify_peer" => $this->https_verify_peer,
|
|
||||||
"verify_peer_name" => $this->https_verify_peer,
|
|
||||||
"allow_self_signed" => !$this->https_verify_peer
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
$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().
|
|
||||||
// The first header line and second word will contain the status code.
|
|
||||||
$resp_code = (int) explode(" ", $http_response_header[0])[1];
|
|
||||||
|
|
||||||
// Return response as [<resp_body_assoc_array>, <http_status_code>]
|
|
||||||
return [$resp, $resp_code];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set request body to be JSON-stringified
|
|
||||||
private function set_request_body(?array $payload = null): self {
|
|
||||||
// Unset request body if no payload defined
|
|
||||||
if (empty($payload)) {
|
|
||||||
$this->payload = null;
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->headers["Content-Type"] = "application/json";
|
|
||||||
|
|
||||||
$this->payload = $payload;
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----
|
|
||||||
|
|
||||||
// Construct URL search parameters from array if set
|
|
||||||
public function params(?array $params = null): self {
|
|
||||||
$this->params = !empty($params) ? self::get_params($params) : "";
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace Reflect;
|
|
||||||
|
|
||||||
// Allowed HTTP verbs
|
|
||||||
enum Method {
|
|
||||||
case GET;
|
|
||||||
case POST;
|
|
||||||
case PUT;
|
|
||||||
case DELETE;
|
|
||||||
case PATCH;
|
|
||||||
case OPTIONS;
|
|
||||||
}
|
|
|
@ -1,30 +0,0 @@
|
||||||
<?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;
|
|
||||||
}
|
|
||||||
}
|
|
43
src/SocketClient.php
Normal file
43
src/SocketClient.php
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Allowed HTTP verbs
|
||||||
|
enum Method: string {
|
||||||
|
case GET = "GET";
|
||||||
|
case POST = "POST";
|
||||||
|
case PUT = "PUT";
|
||||||
|
case DELETE = "DELETE";
|
||||||
|
case PATCH = "PATCH";
|
||||||
|
case OPTIONS = "OPTIONS";
|
||||||
|
}
|
||||||
|
|
||||||
|
class SocketClient {
|
||||||
|
public function __construct(string $path) {
|
||||||
|
$this->socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
|
||||||
|
$conn = socket_connect($this->socket, $path);
|
||||||
|
|
||||||
|
if (!$conn) {
|
||||||
|
throw new Error("Unable to connect to socket");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make request and return response
|
||||||
|
private function txn(string $payload): string {
|
||||||
|
$tx = socket_write($this->socket, $payload, strlen($payload));
|
||||||
|
$rx = socket_read($this->socket, 2024);
|
||||||
|
|
||||||
|
if (!$tx || !$rx) {
|
||||||
|
throw new Error("Failed to complete transaction");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create HTTP-like JSON with ["<endpoint>","<method>","[payload]"]
|
||||||
|
public function call(string $endpoint, Method $method, array $payload = null): mixed {
|
||||||
|
return json_decode($this->txn(json_encode([
|
||||||
|
$endpoint,
|
||||||
|
$method->value,
|
||||||
|
$payload
|
||||||
|
])));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue