Skip to content

Instantly share code, notes, and snippets.

@agungsugiarto
Created September 23, 2022 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agungsugiarto/92bc2705a8a8811867ca9d54ffe8a7f0 to your computer and use it in GitHub Desktop.
Save agungsugiarto/92bc2705a8a8811867ca9d54ffe8a7f0 to your computer and use it in GitHub Desktop.
Scrap Kode Relasi BPS dengan Kemendagri
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
class BPSController extends Controller
{
/**
* @var string
*/
protected $url = 'https://sig.bps.go.id/rest-bridging/';
/**
* @var Collection
*/
protected $provinsi;
/**
* @var Collection
*/
protected $kabupaten;
/**
* @var Collection
*/
protected $kecamatan;
/**
* @var Collection
*/
protected $desa;
public function __invoke()
{
try {
$this->provinsi = collect(json_decode((new Client())->get("{$this->url}getwilayah")->getBody()->getContents(), true));
$this->requests($this->provinsi, 'kabupaten');
$this->requests($this->kabupaten, 'kecamatan');
$this->requests($this->kecamatan, 'desa');
return response($this->desa);
} catch (ClientException $e) {
report($e);
}
}
protected function requests($data, $level = '')
{
$client = new Client(['base_uri' => $this->url]);
$requests = function () use ($client, $data, $level) {
foreach ($data as $value) {
yield function () use ($client, $value, $level) {
return $client->getAsync("getwilayah?level={$level}&parent={$value['kode_bps']}");
};
}
};
$pool = new Pool($client, $requests(), [
'concurrency' => 10,
'fulfilled' => function (Response $response, $index) use ($level) {
$this->{$level}[] = json_decode($response->getBody()->getContents(), true);
},
'rejected' => function (RequestException $reason, $index) {
report($reason);
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete
$promise->wait();
$this->{$level} = collect($this->{$level})->flatten(1)->all();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment