feat: add support for Reflect API keys (#2)

* wip: 1682605782

* wip: 1682607489

* wip: 1682607562

* wip: 1682608764

* wip: 1682609355

* wip: 1682609830

* wip: 1682609969

* feat(doc): add API key reference
This commit is contained in:
Victor Westerlund 2023-04-27 20:26:33 +02:00 committed by GitHub
parent 69c9c5928e
commit c819bc3da2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 74 additions and 31 deletions

View file

@ -9,10 +9,10 @@ Make a request with `Client->call()`. It will always return the response as an a
- The second value is the response body
```php
$client = new Reflect\Client("<API URL or path to UNIX socket>");
$client = new Reflect\Client("<API URL or path to UNIX socket>", "<API key (optional)>");
$client->call("foo", Method::GET); // (array) [200, "bar"]
$client->call("foo", Method::POST, [
$client->call("foo", Reflect\Method::GET); // (array) [200, "bar"]
$client->call("foo", Reflect\Method::POST, [
"foo" => "bar"
]); // (array) [201, "Created"]
@ -34,7 +34,7 @@ Requires PHP 8.1 or newer, and of course a Reflect API endpoint.
```php
require_once "/vendor/autoload.php";
$client = new Reflect\Client("<API URL or path to UNIX socket>");
$client = new Reflect\Client("<API URL or path to UNIX socket>", "<API key (optional)>");
```
3. **Make API request**
@ -42,13 +42,13 @@ Requires PHP 8.1 or newer, and of course a Reflect API endpoint.
Use the `call()` method to perform a request
```php
$client->call("foo?bar=baz", Method::GET);
$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|Yes|A supported [Reflect HTTP method](https://github.com/VictorWesterlund/reflect/wiki/Supported-technologies#http-request-methods) (eg. `Method::GET`)
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
@ -86,6 +86,6 @@ Requires PHP CLI 8.1 or greater, and of course a Reflect API endpoint.
2. **Run from command line**
```
cd reflect-client-php
// From the root directory of this project
php client <url_or_socket_file_path> <endpoint> <http_method> [payload]
```

View file

@ -13,48 +13,88 @@
}
// Supported connection methods
enum ConType {
enum Connection {
case HTTP;
case AF_UNIX;
}
class Client {
public function __construct(string $endpoint, ConType $con = null) {
$this->_con = $con ?: $this::resolve_contype($endpoint);
$this->_endpoint = $endpoint;
// Use this HTTP method if no method specified to call()
const HTTP_DEFAULT_METHOD = Method::GET;
// The amount of bytes to read for each chunk from socket
const SOCKET_READ_BYTES = 2048;
// Initialize socket properties
if ($this->_con === ConType::AF_UNIX) {
$this->socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
$conn = socket_connect($this->socket, $this->_endpoint);
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;
if ($this->_con === Connection::AF_UNIX) {
// Connect to Reflect UNIX socket
$this->_socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
$conn = socket_connect($this->_socket, $this->_endpoint);
} 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.
// 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 resolve_contype(string $endpoint): ConType {
// 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 resolve_connection(string $endpoint): Connection {
return filter_var($endpoint, FILTER_VALIDATE_URL)
? ConType::HTTP
: ConType::AF_UNIX;
? 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
private function http_headers(): string {
$headers = ["Content-Type: application/json"];
// Append Authentication header if API key is provided
if (!empty($this->_key)) {
$headers[] = "Authorization: Bearer {$this->_key}";
}
// Append new line chars to each header
$headers = array_map(fn($header): string => $header . "\r\n", $headers);
return implode("", $headers);
}
// Make request and return response over HTTP
private function http_call(string $endpoint, Method $method, array $payload = null): array {
private function http_call(string $endpoint, Method|string $method = (__CLASS__)::HTTP_DEFAULT_METHOD, array $payload = null): array {
// Resolve string to enum
$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" => [
"header" => "Content-Type: application/json",
"header" => $this->http_headers(),
"method" => $method->value,
"ignore_errors" => true,
"content" => !empty($payload) ? json_encode($payload) : ""
],
"ssl" => [
"verify_peer" => $this->_https_peer_verify,
"verify_peer_name" => $this->_https_peer_verify,
"allow_self_signed" => !$this->_https_peer_verify
]
]);
$resp = file_get_contents($this->_endpoint . $endpoint, false, $data);
// 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.
// 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 [$resp_code, $resp];
@ -62,11 +102,11 @@
// Make request and return response over socket
private function socket_txn(string $payload): string {
$tx = socket_write($this->socket, $payload, strlen($payload));
$rx = socket_read($this->socket, 2024);
$tx = socket_write($this->_socket, $payload, strlen($payload));
$rx = socket_read($this->_socket, $this::SOCKET_READ_BYTES);
if (!$tx || !$rx) {
throw new Error("Failed to complete transaction");
throw new \Error("Failed to complete transaction");
}
return $rx;
@ -74,10 +114,13 @@
// Create HTTP-like JSON with ["<endpoint>","<method>","[payload]"] and return
// respone from endpoint as ["<http_status_code", "<json_encoded_response_body>"]
public function call(string $endpoint, Method $method, array $payload = null): 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
if ($this->_con === ConType::AF_UNIX) {
return json_decode($this->socket_txn(json_encode([
if ($this->_con === Connection::AF_UNIX) {
return json_decode($this->_socket_txn(json_encode([
$endpoint,
$method->value,
$payload