-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
01-transform.php
51 lines (41 loc) · 1.5 KB
/
01-transform.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
<?php
require __DIR__ . '/../vendor/autoload.php';
$browser = new React\Http\Browser();
$concurrency = isset($argv[1]) ? $argv[1] : 3;
// each job should use the browser to GET a certain URL
// limit number of concurrent jobs here
$transformer = new Clue\React\Flux\Transformer($concurrency, function ($user) use ($browser) {
// skip users that do not have an IP address listed
if (!isset($user['ip'])) {
$user['country'] = 'n/a';
return React\Promise\resolve($user);
}
// look up country for this user's IP
return $browser->get("https://ipapi.co/$user[ip]/country_name/")->then(
function (Psr\Http\Message\ResponseInterface $response) use ($user) {
// response successfully received
// add country to user array and return updated user
$user['country'] = (string)$response->getBody();
return $user;
}
);
});
// load a huge number of users to process from NDJSON file
$input = new Clue\React\NDJson\Decoder(
new React\Stream\ReadableResourceStream(
fopen(__DIR__ . '/users.ndjson', 'r')
),
true
);
// process all users by piping through transformer
$input->pipe($transformer);
// log transformed output results
$transformer->on('data', function ($user) {
echo $user['name'] . ' is from ' . $user['country'] . PHP_EOL;
});
$transformer->on('end', function () {
echo '[DONE]' . PHP_EOL;
});
$transformer->on('error', function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});