Skip to content

Commit

Permalink
Add dynamic remote source file method
Browse files Browse the repository at this point in the history
  • Loading branch information
fatihtoprak committed Feb 24, 2022
1 parent 149ec3e commit f1ae125
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 947,389 deletions.
86 changes: 83 additions & 3 deletions src/Seeders/LCSCSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,17 @@ class LCSCSeeder extends Seeder
public function run()
{
ini_set('memory_limit', '-1');
$countries = json_decode(file_get_contents(__DIR__ . "/../countries+states+cities.json"));


$remoteJson = 'https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/countries+states+cities.json';

$fileSize = $this->remoteFileSize($remoteJson);

$this->info('Fetching countries from remote source...['.$fileSize.']');


$countries = $this->remoteGet($remoteJson);
//$countries = json_decode(file_get_contents(__DIR__ . "/../countries+states+cities.json"));
foreach ($countries as $countryData) {
$country = Country::query()->updateOrCreate(
[
Expand All @@ -32,7 +42,7 @@ public function run()
"latitude" => $countryData->latitude,
"longitude" => $countryData->longitude,
]);
echo "Adding " . $country->name . " state and cities... ";
$this->info("Adding " . $country->name . " state and cities... ");

foreach ($countryData->states as $stateData) {
$state = State::query()->updateOrCreate(
Expand All @@ -58,8 +68,78 @@ public function run()
]);
}
}
echo "done." . PHP_EOL;
$this->info("done." . PHP_EOL);
}

}

/**
* Get Remote File
*
* @param [string] $url
* @return void
*/
private function remoteGet( $url ) : string
{
$ch = curl_init();

curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$data = curl_exec($ch);
curl_close($ch);

return $data;
}

/**
* Get file size from remote source
*
* @param [string] $url
* @return void
*/
private function remoteFileSize( $url )
{
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);

$data = curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

curl_close($ch);


$bytes = $size;

if ($bytes > 0)
{
$unit = intval(log($bytes, 1024));
$units = array('B', 'KB', 'MB', 'GB');

if (array_key_exists($unit, $units) === true)
{
return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
}
}

return $bytes;

}

/**
* Console output
*
* @param [string] $string
* @return void
*/
private function info($string)
{
echo $string . PHP_EOL;
}
}
Loading

0 comments on commit f1ae125

Please sign in to comment.