-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path04-multiple-concurrent-fetch.php
57 lines (48 loc) · 1.58 KB
/
04-multiple-concurrent-fetch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
require(implode(DIRECTORY_SEPARATOR, ["..", "vendor", "autoload.php"]));
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();