Skip to content

Commit

Permalink
Examples (#61)
Browse files Browse the repository at this point in the history
* docs: add examples

* docs: add description to examples

* docs: add streaming example
  • Loading branch information
g105b authored Sep 7, 2022
1 parent 22a6558 commit c5fde51
Show file tree
Hide file tree
Showing 9 changed files with 298 additions and 33 deletions.
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,13 @@ Example using PHP.Gt/Curl:
--------------------------

```php
$curl = new Curl("https://circleci.com/api/v1.1/project/github/PhpGt/Dom");
$curl = new Curl("https://catfact.ninja/fact");
$curl->exec();
$json = $curl->outputJson();
echo "Latest build status: " . $json[0]->status;
echo "Here's a cat fact: {$json->getString("fact")}";
echo PHP_EOL;
echo "The fact's length is {$json->getInt("length")} characters.";
echo PHP_EOL;
```

Same example using PHP's native `curl_*` functions:
Expand All @@ -43,7 +46,7 @@ Same example using PHP's native `curl_*` functions:
```php
// Using native functionality to achieve the same:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://circleci.com/api/v1.1/project/github/PhpGt/Dom");
curl_setopt($ch, CURLOPT_URL, "https://catfact.ninja/fact");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(false === $result) {
Expand All @@ -53,5 +56,10 @@ $json = json_decode($result);
if(is_null($json)) {
die("JSON decoding error: " . json_last_error_msg());
}
echo "Latest build status: " . $json[0]->status;
```

// Note: No type checks are made on the `fact` and `length` properties here.
echo "Here's a cat fact: {$json->fact}";
echo PHP_EOL;
echo "The fact's length is {$json->length} characters.";
echo PHP_EOL;
```
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
"type": "library",

"require": {
"php": ">=7.2.0",
"php": ">=7.4",
"ext-curl": "*",
"ext-json": "*"
"ext-json": "*",
"phpgt/json": "^v1.0"
},

"require-dev": {
Expand Down
161 changes: 158 additions & 3 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions examples/01-json-usage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/*
This example shows how to load a JSON API and interact with the response in a
type-safe way. This utilises https://php.gt/json for the response object.
*/
use Gt\Curl\Curl;

require(__DIR__ . "/../vendor/autoload.php");

$curl = new Curl("https://catfact.ninja/fact");
$curl->exec();
$json = $curl->outputJson();
echo "Here's a cat fact: {$json->getString("fact")}";
echo PHP_EOL;
echo "The fact's length is {$json->getInt("length")} characters.";
echo PHP_EOL;

/* Example output:
Here's a cat fact: Phoenician cargo ships are thought to have brought the first domesticated cats to Europe in about 900 BC.
The fact's length is 105 characters.
*/
36 changes: 36 additions & 0 deletions examples/02-curl-multi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/*
* This example shows how more than one Curl request can be executed
* simultaneously by adding the Curl object to a CurlMulti object. This means
* the total time waiting for N responses is equal to the slowest response,
* rather than the sum of all responses.
*/
use Gt\Curl\Curl;
use Gt\Curl\CurlMulti;

require(__DIR__ . "/../vendor/autoload.php");

$curlCat = new Curl("https://catfact.ninja/fact");
$curlCat->setOpt(CURLOPT_RETURNTRANSFER, true);
$curlIp = new Curl("https://api.ipify.org/?format=json");
$curlIp->setOpt(CURLOPT_RETURNTRANSFER, true);
$curlTimeout = new Curl("https://this-domain-name-does-not-exist.example.com/nothing.json");
$curlTimeout->setOpt(CURLOPT_RETURNTRANSFER, true);

$multi = new CurlMulti();
$multi->add($curlCat);
$multi->add($curlIp);
$multi->add($curlTimeout);

$stillRunning = 0;
do {
$multi->exec($stillRunning);
usleep(100_000);
echo ".";
}
while($stillRunning > 0);

echo PHP_EOL;
echo "Cat API response: " . $multi->getContent($curlCat) . PHP_EOL;
echo "IP API response: " . $multi->getContent($curlIp) . PHP_EOL;
echo "Timeout API response: " . $multi->getContent($curlTimeout) . PHP_EOL;
48 changes: 48 additions & 0 deletions examples/03-curl-multi-streaming.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/*
* In the previous curl-multi example, all response data is buffered, but under
* some circumstances it is useful to get the response data as soon as it's
* received, even if the response hasn't completed yet.
*
* With CurlMulti, we can stream the data byte for byte as it's received. This
* is especially useful for processing data on slow or long-running responses.
*
* Notice how the dots are emitted every 100 microseconds, and the content is
* streamed during the execution (within the while loop).
*/

use Gt\Curl\Curl;
use Gt\Curl\CurlMulti;

require(__DIR__ . "/../vendor/autoload.php");

$urlArray = [
"https://catfact.ninja/fact",
"https://api.ipify.org/?format=json",
"https://this-domain-name-does-not-exist.example.com/nothing.json",
];

$multi = new CurlMulti();

foreach($urlArray as $url) {
$curl = new Curl($url);
$curl->setOpt(CURLOPT_HEADERFUNCTION, function ($ch, string $rawHeader):int {
echo "HEADER: $rawHeader";
return strlen($rawHeader);
});
$curl->setOpt(CURLOPT_WRITEFUNCTION, function ($ch, string $rawBody):int {
echo "BODY: $rawBody\n";
return strlen($rawBody);
});
$multi->add($curl);
}

$stillRunning = 0;
do {
$multi->exec($stillRunning);
usleep(10_000);
echo ".";
}
while($stillRunning > 0);

echo PHP_EOL;
31 changes: 13 additions & 18 deletions src/Curl.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?php
namespace Gt\Curl;

use Gt\Json\JsonObject;
use Gt\Json\JsonObjectBuilder;

class Curl implements CurlInterface {
/** @var resource */
protected $ch;
/** @var string */
protected $buffer;
protected string $buffer;

public function __construct(string $url = null) {
$this->init($url);
Expand Down Expand Up @@ -73,19 +75,9 @@ public function output():string {
public function outputJson(
int $depth = 512,
int $options = 0
) {
$json = json_decode(
$this->output(),
false,
$depth,
$options
);
if(is_null($json)) {
$errorMessage = json_last_error_msg();
throw new JsonDecodeException($errorMessage);
}

return $json;
):JsonObject {
$builder = new JsonObjectBuilder();
return $builder->fromJsonString($this->output());
}

/**
Expand Down Expand Up @@ -128,7 +120,7 @@ public function exec():string {
if(true === $response) {
$response = $this->buffer;
}

return $response;
}

Expand Down Expand Up @@ -207,6 +199,9 @@ public function getHandle(){
* Gets all CURLINFO_ data, identical to calling curl_getinfo with no arguments.
*/
public function getAllInfo():array {
return curl_getinfo($this->ch, 0);
$result = curl_getinfo($this->ch, 0);
if(!$result) {
return [];
}
}
}
}
Loading

0 comments on commit c5fde51

Please sign in to comment.