-
-
Notifications
You must be signed in to change notification settings - Fork 9
Usage examples
You can run all of these examples from the examples/
directory of this project's repository.
Here we are performing a basic fetch of a JSON endpoint. The endpoint is https://api.github.com/orgs/phpgt/repos and it lists all of the PHP.GT repositories along with other information.
use Gt\Fetch\Http;
use Gt\Http\Response;
use Gt\Json\JsonKvpObject;
use Gt\Json\JsonPrimitive\JsonArrayPrimitive;
$http = new Http();
$http->fetch("https://api.github.com/orgs/phpgt/repos")
->then(function(Response $response) {
echo "Got a response. Processing JSON... ", PHP_EOL;
if(!$response->ok) {
throw new RuntimeException("Can't retrieve Github's API on $response->uri");
}
return $response->json();
})
->then(function(JsonArrayPrimitive $json) {
echo "SUCCESS: Json promise resolved!", PHP_EOL, PHP_EOL;
echo "PHP.Gt has the following repositories: ";
$repoList = [];
/** @var JsonKvpObject $item */
foreach($json->getPrimitiveValue() as $item) {
array_push($repoList, $item->getString("name"));
}
echo wordwrap(implode(", ", $repoList)) . ".";
echo PHP_EOL, PHP_EOL;
})
->catch(function(Throwable $reason) {
echo "There was an error!",
PHP_EOL,
get_class($reason),
" - ",
$reason->getMessage(),
" ",
$reason->getFile(),
":", $reason->getLine(),
PHP_EOL, PHP_EOL;
});
$http->wait();
Example output:
Got a response. Processing JSON...
SUCCESS: Json promise resolved!
PHP.Gt has the following repositories: WebEngine, Dom, Csrf, Config, www.php.gt, Database, StyleGuide, Fetch,
Curl, DomTemplate, Build, Http, Input, Cookie, Session, ProtectedGlobal,
CssXPath, Cli, DomValidation, Installer, SqlBuilder, Cron, Logger, Server,
Daemon, Sync, Async, Promise, TypeSafeGetter, DataObject.
This example performs a POST request to the postman-echo web service. Posting data to this service will echo it back in the response, along with metadata about the request and response. It's a useful service for testing APIs.
use Gt\Fetch\Http;
use Gt\Http\FormData;
use Gt\Http\Response;
use Gt\Json\JsonObject;
/*
* This example uses postman-echo.com do test the request/response.
* See https://docs.postman-echo.com/ for more information.
*/
// Example: Post form data to the echo server.
$formData = new FormData();
$formData->set("name", "Mark Zuckerberg");
$formData->set("dob", "1984-05-14");
$formData->set("email", "zuck@fb.com");
$http = new Http();
$http->fetch("https://postman-echo.com/post", [
// All of the request parameters can be passed directly here, or alternatively
// the fetch() function can take a PSR-7 RequestInterface object.
"method" => "POST",
"body" => $formData,
])
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error posting to Postman Echo.");
}
// Postman Echo servers respond with a JSON representation of the request
// that was received.
return $response->json();
})
->then(function(JsonObject $json) {
echo "The Postman Echo server received the following form fields:";
echo PHP_EOL;
$formObject = $json->getObject("form");
foreach($formObject->asArray() as $key => $value) {
echo "$key = $value" . PHP_EOL;
}
$firstName = strtok($formObject->getString("name"), " ");
$dob = $formObject->getDateTime("dob");
$age = date("Y") - $dob->format("Y");
echo PHP_EOL;
echo "$firstName is $age years old!" . PHP_EOL;
})
->catch(function(Throwable $error) {
echo "An error occurred: ", $error->getMessage();
});
// To execute the above Promise(s), call wait() or all().
$http->wait();
die("done waiting");
Example output:
The Postman Echo server received the following form fields:
name = Mark Zuckerberg
dob = 1984-05-14
email = zuck@fb.com
Mark is 41 years old!
done waiting
This example uses Cat-as-a-Service API to request a random photo of a cat. When the data is received, it's saved to a temporary file on disk.
<?php
use Gt\Fetch\Http;
use Gt\Http\Blob;
use Gt\Http\Response;
/*
* This example uses Cat-as-a-Service API to request a random photo of a cat.
* See https://cataas.com/ for more information.
*/
// Example: Download an image from the API and store in the temp directory.
$http = new Http();
$http->fetch("https://cataas.com/cat")
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error getting a cat. (ERROR $response->status)");
}
echo "Cat as a Service responded with a binary file with the following attributes:" . PHP_EOL;
echo "Response size: " . $response->getHeaderLine("Content-Length") . PHP_EOL;
echo "File type: " . $response->getHeaderLine("Content-Type") . PHP_EOL;
return $response->blob();
})
->then(function(Blob $blob) {
switch($blob->type) {
case "image/jpeg":
$extension = "jpg";
break;
case "image/png":
$extension = "png";
break;
default:
echo $blob->type . " type is not supported." . PHP_EOL;
exit(1);
}
$file = new SplFileObject("/tmp/cat.$extension", "w");
$bytesWritten = $file->fwrite($blob);
echo "Written $bytesWritten bytes." . PHP_EOL;
echo "Photo written to " . $file->getPathname() . PHP_EOL;
})
->catch(function(Throwable $reason) {
echo "There was an error caught: ", $reason->getMessage(), PHP_EOL;
});
// To execute the above Promise(s), call wait() or all().
$http->wait();
Example output:
Cat as a Service responded with a binary file with the following attributes:
Response size: 212471
File type: image/jpeg
Written 212468 bytes.
Photo written to /tmp/cat.jpg
Example file contents at /tmp/cat.jpg:
Here we will perform the same requests as in examples 1-3 above, but this time the requests will be dispatched and processed concurrently. There is no guarantee which response will resolve first, but once $http->wait()
is called, all of the work will be completed before the next line of PHP is hit - the output "Done!" will only appear after all HTTP activity has completed.
use Gt\Fetch\Http;
use Gt\Http\Blob;
use Gt\Http\Response;
use Gt\Json\JsonKvpObject;
use Gt\Json\JsonPrimitive\JsonArrayPrimitive;
$getJsonFromResponse = function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Can't retrieve Github's API on $response->uri");
}
return $response->json();
};
$listReposFromJson = function(JsonArrayPrimitive $json) {
echo "SUCCESS: Json promise resolved!", PHP_EOL;
echo "PHP.Gt has the following repositories: ";
$repoList = [];
/** @var JsonKvpObject $item */
foreach($json->getPrimitiveValue() as $item) {
array_push($repoList, $item->getString("name"));
}
echo wordwrap(implode(", ", $repoList)) . ".";
echo PHP_EOL, PHP_EOL;
};
$errorHandler = function(Throwable $reason) {
echo "ERROR: ", PHP_EOL, $reason->getMessage(), PHP_EOL, PHP_EOL;
};
$http = new Http();
$http->fetch("https://api.github.com/orgs/phpgt/repos")
->then($getJsonFromResponse)
->then($listReposFromJson)
->catch($errorHandler);
$http->fetch("https://github.com/phpgt/__this-does-not-exist")
->then($getJsonFromResponse)
->then($listReposFromJson)
->catch($errorHandler);
$http->fetch("https://cataas.com/cat")
->then(function(Response $response) {
return $response->blob();
})
->then(function(Blob $blob) {
$file = new SplFileObject("/tmp/cat", "w");
$bytesWritten = $file->fwrite($blob);
echo "Written $bytesWritten bytes.", PHP_EOL;
echo "Type: $blob->type", PHP_EOL;
echo "Photo written to ", $file->getPathname(), PHP_EOL, PHP_EOL;
});
$http->wait();
echo "Done!", PHP_EOL;
Fetch is not just for downloading HTTP responses. Part of the request can contain data, such as form data or in this case, a file upload. In this example, the script creates a new SplFileObject
pointing to itself, and then uploads the script to postman-echo.com.
After the file has uploaded, we check the response and echo the size of the file received on the server.
use Gt\Fetch\Http;
use Gt\Http\FormData;
use Gt\Http\Response;
use Gt\Json\JsonObject;
$formData = new FormData();
$formData->set("upload", new SplFileObject(__FILE__));
$http = new Http();
$http->fetch("https://postman-echo.com/post", [
"method" => "POST",
"headers" => [
"Content-type" => "multipart/form-data"
],
"body" => $formData,
])
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error uploading file to Postman Echo.");
}
return $response->json();
})
->then(function(JsonObject $json) {
foreach($json->asArray()["files"] as $fileName => $data) {
echo $fileName . " - " . strlen($data) . " bytes", PHP_EOL;
}
})
->catch(function(Throwable $error) {
echo "An error occurred: ", $error->getMessage();
});
$http->wait();
die("done waiting");
Example output:
05-upload-file.php - 1237 bytes
done waiting
PHP.Gt/Fetch is a separately maintained component of PHP.Gt/WebEngine.